Consider:
struct
{
char *rcssMonitoredServices;
int nSomeVar;
} appinfo;
In conventional use:
appinfo.rcssMonitoredServices=strdup("something");
However now consider:
char *RefToStructVar[]=
{
appinfo.rcssMonitoredServices,
"\0"
};
The intent being that we may perform operations against appinfo.rcssMonitoredServices using the RegToStructVar[0] pointer.
There are good reasons why I have variables pointed to within arrays. In cases of integer variables, we’re A-OK. Pointers to *char are quite different.
If I am doing the same technique against appinfo.nSomeVar
int *varpointers[] =
{
&appinfo.nSomeVar,
0
};
varpointers[0]=196;
printf("%i",appinfo.nSomeVar) // -> "196"
I thought that, given RefToStructVar[0] contains a pointer to the appinfo.rcssMonitoredServices, doing things like
RefToStructVar[0]=strdup("something");
Would be identical to:
appinfo.rcssMonitoredServices=strdup("something");
But no.
This
RefToStructVar[0]=strdup("something");
segfaults.
Perhaps basic.. but at the moment I am muddled.
—
later
Here’s what segfaults:
struct
{
char *cVar;
int n;
} mystruct;
char *aVars[]=
{
mystruct.cVar,
"\0"
};
aVars[0]=strdup("something");
This works:
struct
{
char *cVar;
int n;
} mystruct;
char **aVars[]=
{
&mystruct.cVar,
"\0"
};
*aVars[0]=strdup("something");
Is not identical to
Because although the two pointers point to the same memory, they are two different pointers, and assigning to one of them will not change the other.
Also, there is absolutely no reason why
RefToStructVar[0] = anythingshould segfault unlessRefToStructVaris not an array but an invalid pointer or something. I think you are misdiagnosing the crash site.You say:
However, that’s not what it’s doing. It’s simply copying the pointer from
appinfointo the array. You can do operations on the string such as changing a character that way, but if you assign to either one, they become independent. You need a pointer to a pointer if you want to do that: