I keep recieving an error message when I run the code. The error message is, \"S
ID: 3826141 • Letter: I
Question
I keep recieving an error message when I run the code. The error message is, "Segmentation fault (core dumped)". I input ./myoutput CSCE 3600 ENGL 1234 and the output should be . S 3 N 1 but I get the core dumped error message. The code is listed below.
#include<stdio.h>
#include<string.h>
int main(int argc, char *argv[])
{
int i;
if(argc < 2 || argc > 6)
{
printf("Must have 2 to 6 arguments.");
}
else
for(i=0; i<argc; i+=3)
{
printf("%c %c ", argv[i][0], argv[i+1][1]);
}
printf(" ");
return 0;
}
Explanation / Answer
Ans: Segmentation fault (core dumped) error occurs when we try to access memory that we we dont having accedd.
I made small changes to code and cleared.
** You should also check whether that argc is atleast 2 before accessing the argv[i]
#include<stdio.h>
#include<string.h>
int main(int argc, char *argv[])
{
int i;
if(argc < 2 || argc > 6)
{
printf("Must have 2 to 6 arguments.");
}
else
for(i=0; i<argc; i+=3)
{
printf("%d %d ", argv[i][0], argv[i+1][1]);
}
printf(" ");
return 0;
}