I am writing a code to take input from the user, and print it out exactly as it was input, through arrays.
void getArrays(char a[10][10], int b[10], int n ){
printf("Enter number of students and then those students names and scores separated by a space.\n");
scanf("%d", &n);
int i = 0;
while(i < n){
scanf("%s%d", a[i],&b[i]);
i++;
}
}
void printArrays(char a[10][10], int b[10], int n ){
int j;
for(j=0; j<n-1; j++){
printf("%s %d\n", a[j],b[j] );
}
}
In this scenario a
is a character array that is 10 rows by 10 columns, while b
is an array of ints, sized 10 rows as well. n
is a number entered by the user before the arrays are created, specifying the amount of strings to be in the arrays.
The input would look something like this:
5
Jimmy 90
Tony 80
Troy 67
Dona 78
Dylan 97
At this point it cuts off, and prints the arrays, which worked properly. However, after the names were done printing, the terminal spit a multitude of numbers and random strings before giving me this error:
Segmentation Fault (core dumped)
I ran it through the gbd debugger, and was given the following message:
Program received signal SIGSEGV, Segmentation fault.
__strlen_avx2 () at ../sysdeps/x86_64/multiarch/strlen-avx2.S:65
65 ../sysdeps/x86_64/multiarch/strlen-avx2.S: No such file or directory.
I've searched this error on the site, but the questions already asked didn't relate to my issue; Weird Segmentation Fault after printing Segmentation fault core dump These are just two of the ones I've seen, and they were not the answer I was looking for.
I saw from further searches that it could be a pointer error, or a size discrepancy in the code when referring to an array. I narrowed the problem down to only occurring after it finished printing out the names. So I tried to change for(j=0; j<n; j++)
to for(j=0; j<n-1; j++)
, and once again it gave me the same issues.
I think perhaps the for loop is reading past the number of elements I want it to, ie- instead of stopping at 3, (if n
= 3), and it has nothing else to print so it gives me the segmentation fault error?
Do I need to use a pointer with n
in this case, such as &n
, or is the issue going to be with the size of my array?
The code that calls these functions is as follows:
int main(){
char names[10][15]; // can handle up to 10 students
int scores[10];
int num;
int average;
getScores(names, scores, num);
printScores(names, scores, num);
}