Hello I have a function which populates a 2D array, consisting of words. I want to simply return the value of the pointer I entered the function with, but for some reason the pointer is now pointing to something else, strangely. I want to know how to fix this. Also wouldn't it be possible to do pointer arithmetic to fix this issue?(That's not what I want to do, I want to see what the issue is and fix it that way, but it'd be nice to know anyway). So it's supposed to be a 500 x 5 array, and even though I assign strings to 'dictPointer[i]', which I thought is supposed to represent "*dictPointer" and not "dictPointer", it seems as though I shouldn't have an issue. I need it to be this way because I wanted to print words starting from the initial pointer value. Also note that dictPointer is a pointer to pointer( **dictPointer)
char** readAndPopulateArray(FILE *f, char *fileName, char **dictPointer, int x ) { // x represents the number of words
// point is the word pointer
int i = 0;
char tempStr[80];
char ch;
f = fopen(fileName, "r");
if ( f == NULL ) {
printf("Cannot open %s. Verify it's in the right location\n", fileName);
}
while (fscanf(f, "%s", tempStr) == 1 ) {
if( strlen(tempStr) == 4 ) {
if(i == 0 ) {
printf("Entering dictpointer points to %p\n", *dictPointer);
}
dictPointer[i] = tempStr;
if ( i == 499 ) {
printf("Exiting dictPointer points to %p\n", *dictPointer);
}
}
i++;
}
return dictPointer;
}
Below was how I called malloc for the matrix:
char** makeStringWordArray(int x, int letters ) { // x represents number of words, function stores one character each per word
// letters represents number of letters in each word
char *hold;
int i, j = 0;
char **dict = (char **)(malloc(x * sizeof(char*)) );
for (i = 0; i<x; i++ ) {
dict[i] = (char*)(malloc(letters*sizeof(char) + 1 ) );
}
return dict;
}
答案 0 :(得分:1)
You assign every dictPointer[i]
to the same pointer tempStr
. Then the lifetime of tempStr
ends at the end of readAndPopulateArray
, making dictPointer[i]
invalid.
Perhaps you meant
strcpy(dictPointer[i], tempStr);