The following is an abstract version of a problem I am currently having.
#include <stdio.h>
int main()
{
typedef struct {
char * bar
} struct_t;
struct_t foo = {};
foo.bar = "test";
struct_t * p_foo = &foo;
char * p = p_foo->bar;
char ** a = &p_foo;
char ** b = &p_foo->bar;
printf("%s %s",*a,*b);
return 0;
}
I expect the code to print test twice, which it doesn't. Why is that happening?
******************************* EDIT *******************************
The abstraction I WANTED to post is the following, it's basically what you guys pointed out to be wrong in my first attempt - thanks for that.
#include <stdio.h>
int main()
{
typedef struct {
char * bar;
} struct_t;
struct_t foo = { .bar = "test" };
// works
struct_t * p_foo = &foo;
char * p_bar = &p_foo->bar[0];
char ** a = &p_bar;
// does not work
char ** b = &p_foo->bar;
printf("%s %s",*a,*b);
return 0;
}
However, this version does actually print test twice, meaning that the abstraction does not reproduce my problem, so I have to try once again:
#include <stdio.h>
void callback(void ** ppContext)
{
char * pString = (char *) *(ppContext);
printf("%s",pString);
}
int main()
{
typedef struct {
char buffer[5];
} struct_t;
struct_t ctrl = { .buffer = "test" };
struct_t * pCtrl = &ctrl;
// works
char * pString = &pCtrl->buffer[0];
callback((void **) &pString);
// does not work
callback((void **) &pCtrl->buffer);
return 0;
}
This is the actual code, I just deleted everything non-related. The section named //works prints test as expected. The section named //does not work does not.
(I commented out one of them respectively to test it, an fflush inbetween them would make testing them simultaneously possible.)
I expect &pCtrl->buffer[0] to be the address of the first char in the buffer which is stored in pString. Since the callback is called with the address of pString, the (char *) *(ppContext) in the callback makes it the actuall string again, i.e., a pointer to the first char in the buffer.
However, I would expect &pCtrl->buffer to be the address of the string as well, if pCtrl->buffer is the string itself, i.e., the address of the first char in the buffer. But apparantly that is not the case and I don't understand why.
a = &p_foois a pointer top_foo.p_foois a pointer and points tofoo. By doing*ayou are trying to print the value of the pointerp_foo, i.e. the address offooitself, as a string.If you really want to do that, you might dereference
ato getp_fooand then dereferencep_footo get the address offoowhich is equal to the address offoo.barwhich holds the address of the string to be printed:But really, your code breaks language constraints and is invalid. You should use correct types and properly access structure members: