I wrote a simple program to take names and numbers from the user and store it in an array, then compare between each cell until it reach the maximum grade then it displays it. The problem is that when it run it shows a message (segmentation fault (Core dump)). I really don't know what my mistake is.
#include <stdio.h>
int main() {
int n;
printf("Enter the number of students: ");
scanf("%d", & n);
char name[n];
float score[n];
for (int i = 0; i < n; i ) {
printf("\nEnter the name of Student: ");
scanf("%s", & name[i]);
printf("\nEnter the score: ");
scanf("%f", & score[i]);
}
float max;
int index;
max = score[0];
index = 0;
for (int i = 1; i < n; i ) {
if (max < score[i]) {
max = score[i];
index = i;
}
}
printf("\nHighest mark scored is %f by student %s", name[index], score[index]);
}
CodePudding user response:
1- you use user input to define the size of an array (wrong)
-- array in c has static size so you must define it's size before the code reach the compiling stage(use dynamic memory allocation instead)
2- scanf("%s", & name[I]); you want to save array of char and save the address at the name variable but name it self not a pointer to save address it's just of char type (wrong)
-- you need pointer to save the address of every name so it's array of pointer and a pointer to allocate the address of the array to it so it's a pointer to poiner and define max size of word if you define size the user input exceed it will produce an error
3- finally you exchanged the %f,%s in printf
#include <stdlib.h>
#include <stdio.h>
#define SIZE_OF_WORD 10
int main() {
int n;
printf("Enter the number of students: ");
scanf("%d", & n);
char **name=(char**)malloc((sizeof(char*)*n));
for (int i = 0; i < n; i ) {
name[i]=(char*)malloc((sizeof(char)*SIZE_OF_WORD));
}
float *score=(float*)malloc((sizeof(float)*n));
for (int i = 0; i < n; i ) {
printf("\nEnter the name of Student: ");
scanf("%s", name[i]);
printf("\nEnter the score: ");
scanf("%f", & score[i]);
}
float max;
int index;
max = score[0];
index = 0;
for (int i = 1; i < n; i ) {
if (max < score[i]) {
max = score[i];
index = i;
}
}
printf("\nHighest mark scored is %s by student %.0f\n", name[index],score[index]);
}