I'm scanning a file to see if user input matches a word in the txt file.. if it matches.. increase the array size and add the word. This is a 2d array. "max_word_size" is currently just a constant variable.

void UserMode(char userAnswers[][max_word_size], int *size)
{
	FILE *fid = fopen("dict.txt","r");
	char dictWord[max_word_size], userWord[max_word_size];
	bool found;
	int i;

	
	{
		printf("Enter a word to check: ");
		scanf("%s", userWord);
		for (i=0; i<strlen(userWord); ++i)
			userWord[i] = tolower(userWord[i]);
		found = false;
		while (!feof(fid) && userWord != dictWord)
		{
			fscanf(fid, "%s", dictWord);
			if (strcmp(dictWord, userWord) == 0)
			{
				printf("Found the word in dictionary!  Saving answer.\n");
				found = true;
				strcpy(userAnswers[*size - 1],userWord);
				++(*size);
				system("pause");
			    realloc(userAnswers, sizeof(char) * int(max_word_size));
			
			}
		}		
		if (!found)
		printf("Could not find word in dictionary! Not saving answer.\n");
		
	
	}
}

Edited 6 Years Ago by DJPlayer: n/a

1. userWord != dictWord for the while loop is wrong instead use false == found.
2. Close the file while exiting the function.
3. realloc(userAnswers, sizeof(char) * int(max_word_size)); should have been realloc(userAnswers, sizeof(char) * int(max_word_size) * size);

you can't realloc() an array what was not a pointer to begin with. you could declare userAnswers as a char***. I've already convered similar situation in another thread here, so I won't repeat it. Just follow the syntax in the other thread how to do it. See my last post in this thread.. It requires three stars because the function needs a pointer to a two-dimensional array.

One difference between that other thread and yours is that your program may need to reallocate the entire array of pointers so that it can hold more strings. That is not very difficult if you keep two counters -- one counter contains the number of char strings that the array can hold (the array's capacity) and another integer that is the number of strings the array currently holds. capacity may be larger than size, but never smaller. When size increases to capacity, then the array needs to be reallocated and capacity increased to the new value.

void UserMode(char ***userAnswers, int* size, int* capacity)
{

}

Edited 6 Years Ago by Ancient Dragon: n/a

I missed that point Ancient Dragon is right you can't realloc() an array which is not a pointer.

which makes it sounds like I'm gonna have to modify more than just the area where it realloc's. I sorta realized the issue after he mentioned that and I realized the realloc returns a points to a position. (first time using realloc, malloc etc..)

This article has been dead for over six months. Start a new discussion instead.