Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Not dereferencing produces a warning when compiling

I’m struggling to understand the nuances of char arrays and string literals, and I’m quite confused as to why the following code produces a warning when I compile it.

warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[4]’ [-Wformat=]
#include <stdio.h>
#include <stdlib.h>

int main(){
    char str_arr[4] = "abc";
    char (*p)[4];
    p = &str_arr;
    printf("A single character: %c\n",(*p)[1]);  
    printf("The entire string: %s\n",p); // When I replace p with *p, the warning goes away, why?
    return 0;
}

If I understand correctly, p is a pointer to a char array of size 4 and after assigning it, it now points to the char array str_array. If we dereference p that gives us the entire char array, but doesn’t %s require a char* as an argument? If we have a char array in place of a char pointer in the argument, shouldn’t that produce a warning?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The format %s expects an argument of type char *. The type of p is not char *. But when you dereference p, with *p, you get an array of char that will decay to char *.

Some compilers are able to detect format-string and argument mismatch and warn about it, because it will lead to undefined behavior.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading