Reputation: 15
I don't understand why the first value of my array is changed outside the inner while loop when the "i" increments correctly. Am I allocating memory in a way that messes something up? How do I go about correcting this issue?
int main(void)
{
int sizeArray = 5, sizeString = 10;
FILE *fin = fopen("file.txt", "r");
char ** arr = (char **) malloc(sizeArray * sizeof(char *));
char line[1000];
char *word;
int i = 0;
while(fgets(line, 100, fin) != NULL)
{
word = strtok(line, " ");
while (i < 2)
{
arr[i] = (char *)malloc(sizeString * sizeof(char));
arr[i] = word;
printf("Inner print: %s\n\n",arr[0]);
word = strtok(NULL, " ");
i++;
}
}
printf("This is the final arr[0] (outer print): %s",arr[0]);
}
file.txt reads as:
First second.
Third! Fourth
The print from my console is as follows:
Inner print: First
Inner print: First
The final arr[0] (outer print): Third!
When I want the outer print to be: First
Upvotes: 0
Views: 77
Reputation: 31296
You need to move int i = 0;
inside the outer while loop. Or to the very least reset it to zero when the inner loop is done.
arr[i] = word
is not how you copy strings in C. Have a look at strcpy
, or even better, strncpy
.
Performing arr[i] = word
right after you have done arr[i] = (char *)malloc
makes the malloc
completely useless. The ONLY thing this accomplishes is to allocate space and then throw the pointer away, yielding a memory leak.
Upvotes: 0
Reputation: 32732
You allocate some memory with arr[i] = (char *)malloc(sizeString * sizeof(char));
. You then immediately overwrite that pointer (leaking the memory) with arr[i] = word
, so that arr[i]
now points somewhere in the line
buffer.
You need to copy the string pointed to by word
into the buffer allocated for arr[i]
:
strcpy_s(arr[i], sizeString * sizeof(char), word);
Upvotes: 1