Format specifier for a pointer to a structure

5.2k Views Asked by At
#include<stdio.h>
#include<stdlib.h>

struct Graph
{
     int v;
};

int main()
{
    struct Graph* graph = (struct Graph*) malloc(sizeof(struct Graph));
    graph -> v = 1;
    printf("%u", graph);
    return 0;
}

But I get a warning regarding the format in line:

printf("%u", graph);

The warning is:

/home/praveen/Dropbox/algo/c_codes/r_2e/main.c|14|warning: format ‘%u’ expects argument of type ‘unsigned int’, but argument 2 has type ‘struct Graph *’ [-Wformat=]|

What format specifier should I use for type struct Graph *?

3

There are 3 best solutions below

0
On BEST ANSWER

The C standard only specifies format specifiers for pre-defined types. The extended MACROs are there to print the fixed-width integers but there exist no format specifier for whole user-defined / aggregate types.

You don't have a format specifier for an array, a structure etc. You have to take individual elements/ members and print them according to their type. You need to understand what is the data (type) that you want to print, and use the appropriate format specifier.

In your case, you can print the member V, which is of type int. So you can do something like

 printf("%d", graph->V);

or, if you want to print the pointer returned by malloc() and stored into graph, you can do

  printf("%p", (void *)graph);

Finally, see this discussion on why not to cast the return value of malloc() and family in C.

8
On

The compiler is right, graph has another type than unsigned int which would be printed by %u. You probably want graph->V since there is no other numerical member of the struct.

printf("%u", graph->V);

Also note your V has int type while you try to print an unsigned int.

UPDATE

What format specifier should I use for type struct Graph *?

For a pointer, you need the format specifier %p and a cast to the type that it accepts.

printf("%p", (void*)graph);

See online demo.

0
On

See what you will do my friend. Seems you want to print out the value you have assigned to the int v.

You are getting that errors because Variable v has a return type int of which you have not included it your printf... Hence

printf("%u", graph -> v);