Accessing char pointer in structure
typedef struct fred {
char mytype[41];
char* myremark;
} fred_t;
With an instance of that s开发者_高级运维tructure
fred_t* mystruct;
I can print mytype
fprintf (stdout, "%s\n", mystruct->mytype);
but I am failing to get the syntax to print myremark in a similar way.
(It's old code that I'm modifying.)
If the instance has been correctly initialized (i.e. the myremark
points to a valid string), you can print it in the exact same manner.
By the way, to print a string to stdout
you can simply use puts
:
puts(mystruct->mytype);
puts(mystruct->myremark);
myremark
is just a pointer. It's not pointing to anything and, from the looks of it, is not initialized either so you're just going to get some random block of memory.
mytype
has allocated storage (41 bytes, to be precise), and so you get the desired result. myremark
points to nothing.
fprintf (stdout, "%s\n", mystruct->myremark);
fprintf (stdout, "%s\n", mystruct->myremark);
should work if myremark
is properly NULL terminated.
You would use the %s modifier just like you are doing for the array. I am wondering if you ever initialize myremark
to point to a valid string.
The API I'm interfacing with is under documented. Each call is simply documented but there is little guidance on how eveything hangs toghether. There is a small collection of example code. Eventually I found a similar example in an unrelated bit of sample code by searching on "vector" (don't ask). There was a two stage process the first stage identified the instance of the structure, but the memory pointed to by the char* pointer wasn't populated until after a second API call referencing the already identifed structure (efficient as is only gets what the user wants - which is much bigger than the simplified illustration I presented). I was missing this second call.
Almost every one who answered asked whether the pointer pointed to an actual string. They were all right and no matter how I changed my syntax it wasn't going to find anything until after that 2nd call. Thanks to all who replied
精彩评论