1

I want to put the data in array using scanf as below with int value.

int main (){

int size=5;
int marks[size];
int x;

for(x=0; x<size; x++){
    scanf("%d", &marks[x]);
}

for(x=0; x<size; x++){
    printf("The Element at %d is %d\n", x, marks[x]);
}
getch();
return 0;
}

Above code is fine and working but i want to use same with strings array like below example, but its not working.

int main (){

int size=5;
char *name[size];
int x;

for(x=0; x<size; x++){
    scanf("%s", name[x]);
}

for(x=0; x<size; x++){
    printf("The Element at %s is %s\n", x, name[x]);
}

getch();
return 0;
}
  • `char *name[size];` is apparently not exactly what you think it is... `char *` is a pointer to a string, but you must let it point to some allocated memory first, before you can use it for scanf. scanf does not allocate memory for you. – Erich Kitzmueller Mar 02 '17 at 14:07

1 Answers1

0

You did not allocate memory to hold your strings. Do

for(x=0; x<size; x++){
    name[x] = (char*)malloc((size_t)64);
    scanf("%s", name[x]);
    printf("<one>\n");
}
Frank-Rene Schäfer
  • 3,182
  • 27
  • 51