I've noticed that when printing a string via a pointer that the pointer should not be dereferenced. Why?
$ cat c.c
#include <stdio.h>
int main(){
char foo[] = "Meirav";
char *bar = foo;
printf("%s\n", foo);
printf("%s\n", bar); // Why isn't this dereferenced?
printf("%p\n", bar);
return 0;
}
$ gcc -Wextra c.c
$ ./a.out
Meirav
Meirav
0x7fffda789ae0
This is the result of dereferencing the pointer, I receive both a compiler warning and a runtime error:
$ vim c.c
$ grep '&bar' c.c
printf("%s\n", &bar);
$ gcc -Wextra c.c
c.c: In function ‘main’:
c.c:8:2: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char **’ [-Wformat=]
printf("%s\n", &bar);
^
$ ./a.out
Meirav
��~|�
0x7fff7c7eafa0
Why shouldn't the pointer dereferenced?
This is my environment:
$ uname -a
Linux melancholy 3.13.0-48-generic #80-Ubuntu SMP Thu Mar 12 11:16:15 UTC 2015 x86_64 x86_64 x86_64 GNU/Linux
$ cat /proc/version
Linux version 3.13.0-48-generic (buildd@orlo) (gcc version 4.8.2 (Ubuntu 4.8.2-19ubuntu1) ) #80-Ubuntu SMP Thu Mar 12 11:16:15 UTC 2015
$ cat /etc/issue
Ubuntu 14.04.2 LTS \n \l
Aucun commentaire:
Enregistrer un commentaire