Reputation: 23
char text[10];
printf("Enter text[Max characters= 9]: ");
scanf("%[^\n]s",&text);
I wrote this by mistake and kept working with it, later on I noticed the mistake in scanf but my question is why was there no error? 3rd line means save the string at the address of address of first element of the array, correct?
Upvotes: 0
Views: 60
Reputation: 1122
Your a.c source code
#include <stdio.h>
int main()
{
char text[10];
printf("%p\n", text);
printf("%p\n", &text);
printf("Enter text[Max characters= 9]: ");
scanf("%[^\n]s",&text);
printf("%p\n", text);
printf("%p\n", &text);
return 0;
}
As you can see on the following logs
bash-5.1$ gcc a.c -o a
bash-5.1$ ./a
0x7fff602b2166
0x7fff602b2166
Enter text[Max characters= 9]: afaefa
0x7fff602b2166
0x7fff602b2166
Text and &text points to the same address. &text on a scanf doesn't break your code but its redundant.
But if you compile with -Wall flag
bash-5.1$ gcc a.c -o a -Wall
a.c: In function ‘main’:
a.c:8:15: warning: format ‘%[^
’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[10]’ [-Wformat=]
8 | scanf("%[^\n]s",&text);
| ~~~^~ ~~~~~
| | |
| | char (*)[10]
| char *
Upvotes: 2