Hi, all.
Here I have little program which should allocate memory dynamically by using malloc and then read data in from files. Then give address of the data to main, but no can do.
Im coding on WinXP with Bloodshed DEV C++ and MS Visual Express 2005 C++, but code should be C.
These are stripped down versions of the code, because I think my problem lies within the pointers.
Here's the struct, plain and simple:
Main function:
readWords function:
So, in readWords everything is working just fine, it's printing the contents of a file ok. But when it gets back to Main, printing my_words results only some weird stuff.
I checked the addresses with printf("%d" &my_words) and they differ, but I just can't figure out the solution.
So, what I would like to know is how dynamically reserve memory, put some data in there and return it to Main(or some other function), 'cuz now I just can't do it.
I've done my swap(&a, &b) excercises and I understand it(I think so;)), but with malloc, I can't get it to work.
Sorry for my bad english, I hope you guys understand what I'm trying to say here.
All help is highly appreciated!
NJ
Here I have little program which should allocate memory dynamically by using malloc and then read data in from files. Then give address of the data to main, but no can do.
Im coding on WinXP with Bloodshed DEV C++ and MS Visual Express 2005 C++, but code should be C.
These are stripped down versions of the code, because I think my problem lies within the pointers.
Here's the struct, plain and simple:
Code:
typedef struct
{
char word[20];
char word2[20];
}Words;
Code:
void main()
{
Words *my_words;
int i=0;
readwords(&my_words);
for(i=0;i<sizeof(my_words)/sizeof(*my_words);i++)
{
printf("%s is word\n", my_words[i].word);
printf("%s is word2\n", my_words[i].word2);
}
}
Code:
void readWords(Words *mywords);
{
int number_of_words=0;
//here I open file, read number of the words from the file
if ((my_words=malloc(number_of_words*sizeof(*mywords))) == NULL)
{
//report failure
}
while (feof(file)==0 && j<number_of_words)
}
/* here I read the words from a file into my_words[i].word
and my_words[i].word2 */
}
for(i=0;i<sizeof(my_words)/sizeof(*my_words);i++)
{
printf("%s is word\n", my_words[i].word);
printf("%s is word2\n", my_words[i].word2);
}
}
I checked the addresses with printf("%d" &my_words) and they differ, but I just can't figure out the solution.
So, what I would like to know is how dynamically reserve memory, put some data in there and return it to Main(or some other function), 'cuz now I just can't do it.
I've done my swap(&a, &b) excercises and I understand it(I think so;)), but with malloc, I can't get it to work.
Sorry for my bad english, I hope you guys understand what I'm trying to say here.
All help is highly appreciated!
NJ
Comment