0
votes

I have this simple code in C to scan and print a string with a whitespace:

#include <stdio.h>
#include <string.h>
int main()
{
   char myName[50];
   printf("Enter your name: ");
   scanf("%[^\n]s", &myName);
   printf("Your name is: %s", myName);
   return 0;
}

The compiler (gcc, part of the command line tools that come with Xcode on my mac) is returning this error:

name.c: In function ‘main’:
name.c:7: warning: format ‘%[^
’ expects type ‘char *’, but argument 2 has type ‘char (*)[50]’
name.c:7: warning: format ‘%[^
’ expects type ‘char *’, but argument 2 has type ‘char (*)[50]’

What's the problem here?

NOTE: I am required to use scanf. No fgets for me :(

5
you might need to use '&myName[0]'. But I could be wrong - Martin
possible duplicate of Reading a string with scanf - user529758
@Martin it's legal C, because the address of the array and the address of its first element is the same. - Mauren
@Mauren. That is true, but &myName != &myName[0] - Martin

5 Answers

4
votes

You should pass to scanf argument of type char* (format %[^\n]s expects so), but in your code:

char myName[50];
scanf("%[^\n]s", &myName);

you pass an address of myName array (i.e. char (*)[50]). You should change it either to:

scanf("%[^\n]", myName);

or:

scanf("%[^\n]", &myName[0]);
2
votes

What's the problem here?

Well, here it is:

format expects type ‘char *’, but argument has type ‘char (*)[50]’

A pointer to an array is not the same as a pointer to the first element of an array. You should get rid of that & operator.

2
votes

Couple issues

  1. Wrong scanf() format s. The s is not part of the format specifier. The %[] format specifier ends with the ].

  2. Wrong scanf() parameter &myName. Rather than passing the address of &myName, which is type char (*)[50] , simply use myName. This will pass the address of the first element of myName which is a char *, the expected matching type for %[].

Use

scanf("%[^\n]", myName);

Further recommend to consume leading white space and limit text read. The 49 limits the input to 49 characters, leaving 1 more byte for the terminating \0.

scanf(" %49[^\n]", myName);
1
votes

In C, myName (when passed to a function) decays to a pointer to the first element of array (myname) of characters. &myName is a pointer to the array myname. &myName[0] would be a pointer to the first character, which is correct, but looks like you tried stuff at random until you chanced on something that worked.

0
votes

Your problem is that your are passing the address to the pointer of the start of the string, rather than the pointer to the string. Simply, remove the &.

   scanf("%[^\n]", myName);