Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
I'm trying to work on my final project for class, and am reading in a bunch of words from a file. I'm trying to store each word into an array. Here's what I have so far:
int loadData(char *nameList[]) {
char name[30];
int length=0;
FILE *filePointer;
if ((filePointer = fopen("words.txt", "r")) == NULL ) {
printf("File could not be opened.");
} else {
do {
fscanf(filePointer, "%s", name);
printf("%s\n", name);
nameList[length] = name;
length++;
} while (!feof(filePointer));
fclose(filePointer);
}
return length;
}The function is called elsewhere in the code with this:
char *nameList[50];
length = loadData(nameList);The array just fills with garbage. We're not even halfway through class yet, so the instructor has barely even touched pointers. I think I know what the problem is - name is constantly being reassigned, so the pointers are essentially useless. Unfortunately, I don't know how to give each new word a unique address in memory.
Just remember I'm fairly new at this (been programming in Flash for 2 years, but only for 1 month in C), so please try to explain in English.
Many thanks!
Marshall

You can't assign arrays a value using = outside of the declaration in C, so use strcpy(namelist[index], name);
You also haven't told the compiler how big the first dimension of your array *namelist[50] is, so you need to allocate space for that before you can use it. A simple way to get your function working would be to declare a static 2D array, and pass that as an argument to the function.

=======================================================
It's been a while but Don, Anaproxy or IR could probably clarify this. I believe that you are actually storing name as the address for nameList[length]. If I am correct then you would have to dereference this pointer to store actual data at the memory location it points to. Again, I'm sure Don, Anaproxy, IR or someone else could verify and clarify this for you. It's been a good 5 years since I've done any serious C/C++ programming so bare with me.borelli35

![]() |
Visual Basic % Profession...
|
what is crystal report?
|

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |