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.
%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].
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.
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.
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.
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 !
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With