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;
}
1
  • 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. Commented Mar 2, 2017 at 14:07

1 Answer 1

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");
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.