You shouldn't return the address of a non-static variable that is local to the function you're in (which is what you're trying to do).
You have these choices
- make the nWords array static
- make the memory allocation for nWords dynamic (use malloc to create it)
- make the nWords array a global variable instead, and forget the defNouns function altogther.
Here's a static example.
Code:
#include <stdio.h>
typedef struct nountypes
{
char n[15];
} nouns;
nouns *defNouns(void);
int main(void)
{
nouns *nWords;
int i;
nWords = defNouns();
for (i = 0; nWords[i].n[0] != '\0'; i++)
{
puts (nWords[i].n);
}
return 0;
}
nouns *defNouns(void)
{
static nouns nWords[] = {{{"sun"}}, {{"ship"}}, {{"darknes"}}, {{""}}};
return(nWords);
}
And here's a global version
Code:
#include <stdio.h>
typedef struct nountypes
{
char n[15];
} nouns;
#define NWORDS_COUNT 3
nouns nWords[NWORDS_COUNT] = {{{"sun"}}, {{"ship"}}, {{"darknes"}}};
int main(void)
{
int i;
for (i = 0; i < NWORDS_COUNT; i++)
{
puts (nWords[i].n);
}
return 0;
}
If you're up for a malloc version, ask and I'll post one (or someone will probably beat me to it )
I've also shown you two different ways of determining the number of elements in the array. The first code used a zero length string in the structure of the last element of the array. The second code used a #define to hard code the number of elements.