0

I don't know what is wrong with the following code. Maybe scanf_s won't scan the string name.

int main(void)
{
    char *name[20]; 
    printf("What is your name>");
    scanf_s("%s", name);
    printf("Your name is %s\n", name);

    return 0;
}

I changed it but it still does not work:

char *name[20]; 
{
    printf("What is your name>");
    scanf_s("%19s", name);
    printf("Your name is %s\n", name);
    return 0;
}

Yes the following works thanks!!!!!!

int main(void) 
{
    char *name[20]; 
    printf("What is your name>");
    scanf_s("%s", name, 20);
    printf("Your name is %s\n", name);
    return 0;
}
Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • 1
    You still have some problems. The first is that you're creating an array of pointers rather than characters. The second is that you should use sizeof rather than magic numbers. – paxdiablo Sep 25 '13 at 02:16
  • 2
    Also, please don't "answer" your question in your question. – Lee Taylor Sep 25 '13 at 02:35

2 Answers2

3

The line:

char *name[20];

creates an array of twenty character pointers. You probably meant:

char name[20];

In any case, the main problem with scanf("%s") was buffer overflow and that was fixed in scanf_s as per the following extract from the C standard, C11 K.3.5.3.2 The fscanf_s function /4 (my bold):

The fscanf_s function is equivalent to fscanf except that the c, s, and [ conversion specifiers apply to a pair of arguments (unless assignment suppression is indicated by a *).

The first of these arguments is the same as for fscanf. That argument is immediately followed in the argument list by the second argument, which has type rsize_t and gives the number of elements in the array pointed to by the first argument of the pair. If the first argument points to a scalar object, it is considered to be an array of one element.

So the correct form would be something like:

scanf_s ("%s", name, sizeof name);

Keep in mind that the stuff in Annex K (bounds checking interfaces) is an optional part of the standard. If it's not available to you, there is another way to get user input, which also handles more than just stopping overflow (it detects and adjusts for rather than just preventing).

Community
  • 1
  • 1
paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
1

scanf_s is the microsoft api. You should conform the IDE is VS, or you're using the microsoft libary. Besides, you should use char name[20];

int main(void){
char name[20]; 
printf("What is your name>");
scanf_s("%s", name);
printf("Your name is %s\n", name);

return 0;
}
YaleCheung
  • 630
  • 3
  • 9