Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use printf("%s",..) to print a struct, the struct's first variable type is 'char *', why can get a right string stored in 'char *'?

Tags:

c

struct

In C language,define a struct like this:     

typedef struct str
{
    char *s;
    int len;
}str;


int main()
{
    str a;
    a.s = "abc"
    printf("%s", a);
    return 0;
}

the output is: "abc", I want to konw why can get this?
I guess the complier think printf("%s", a) as printf("%s", *&a) because &a is equal to &a.s, so *&a is equal to *&a.s, right?

but if so, if I put the int len at the first in the struct body like this:

typedef struct str
{
    int len;
    char *s;
}str;
int main()
{
    str a;
    a.len = 10;
    printf("%d", a);
}

this time the output is: 10, why?
Maybe compiler read %d so it knows that should print a integer value, only print 4 bytes? I want to get some explain about it.

like image 454
tardis Avatar asked Oct 23 '14 09:10

tardis


People also ask

What is %s in C programming?

%s refers to a string %d refers to an integer %c refers to a character. Therefore: %s%d%s%c\n prints the string "The first character in sting ", %d prints i, %s prints " is ", and %c prints str[0].

How do you print a struct variable?

Printf with #v includes main. Fields that is the structure's name. It includes “main” to distinguish the structure present in different packages. Second possible way is to use function Marshal of package encoding/json.

Can you printf a struct?

To print struct variables in Go, you can use the following methods: Use fmt. Printf() with format “verbs” %+v or %#v . Convert the struct to JSON and print the output.

Can an array of characters be a member of a struct?

A structure may contain elements of different data types – int, char, float, double, etc. It may also contain an array as its member. Such an array is called an array within a structure. An array within a structure is a member of the structure and can be accessed just as we access other elements of the structure.


2 Answers

You must specify which value you want to print, printf and C in general cannot guess :)

typedef struct str
{
    int len;
    char *s;
}str;
int main()
{
    str a;
    a.len = 10; // As you did there, you specify which value from your struct !
    printf("%d", a.len);
}

Otherwise it's undefined behaviour and Segfault is coming !

like image 54
Nicolas Charvoz Avatar answered Oct 18 '22 22:10

Nicolas Charvoz


You're invoking undefined behavior. Enable warnings and errors in your compiler (e.g. gcc -Wall -Wextra -Werror) and your ability to do these shenanigans will disappear.

If you really want to know, it's probably because when you pass a by value to printf(), its first member is the char* and that's what printf() sees when it looks for the string to print. In other words, you got lucky.

like image 26
John Zwinck Avatar answered Oct 18 '22 22:10

John Zwinck