I'm having an issue understanding why I can't make the re-assignment for lastPrefix, on the line specified it gives me a segment fault. I appear to be missing something fundamental.
char * somefunc(char ** strs, int numStrings)
{
char * lastPrefix;
printf("%d\n", *(strs[0]+0));
printf("%d\n", *(strs[1]+0));
printf("%d\n", *(strs[2]+0));
printf("%d\n", *(strs[0]+1));
printf("%d\n", *(strs[1]+1));
printf("%d\n", *(strs[2]+1));
printf("%d\n", *(strs[0]+2));
printf("%d\n", *(strs[1]+2));
printf("%d\n", *(strs[2]+2));
printf("%d\n", *(strs[0]+0));
printf("%d\n", *(strs[1]+0));
printf("%d\n", *(strs[2]+0)); // ALL IS WELL
*lastPrefix = *(strs[1]+0);
*lastPrefix = *(strs[2]+0);
*lastPrefix = *(strs[0]+1); // WILL SEGMENT FAULT HERE
*lastPrefix = *(strs[1]+1);
*lastPrefix = *(strs[2]+1);
}
int main()
{
char * strs[] = {
"flower", "flow", "flight"
};
char * res = somefunc(strs, SIZEOF(strs));
}
Could I also ask for a good reference for C pointers?
When you create any variable, whether it's pointer or data, the initial value of the variable will be some garbage or 0. In your case,
char *lastPrefix;
Is such a variable, which contains some garbage value. You have to give it a valid value using malloc()
or something like that. Or else, when you de reference it(*
), it might points to some inaccessible or even nonexistent memory location. Maybe it points to the middle of your code. Maybe it points to NULL. Memories like that is inaccessible in userspace. So, windows(or linux) kills your program.
What you want to do:
char *lastPrefix;
lastPrefix=malloc(101); //holds strings upto 100 characters
The malloc()
will allocate value into your variable from heap and the program should work okay.
Just remember to free the memory at the end: free(lastPrefix);