M
mike79
Hi all!
I am having problems properly malloc'ing an array. The problem is, I
have a structure called "array" which contains 2 elements, "int
arraySize" (how many elements are in the array) and "wordArray" (the
actual array itself).
The "word structure" consists of 2 elements, "int occurrence" (the
number of times that particular word occurs in say a sentence, and
"char *string" (the actual word itself).
So the two structures look like this:
typedef struct words
{
int occurrence;
char *string;
}word;
typedef struct arrays
{
int arraySize;
word *wordArray;
}array;
So what I am trying to do is create 1 structure of "array" to keep
track of the number of elements(words) contained in that array, and
the array itself.
The "array" structure contains an array of "word" structures. And the
"word" structure contains an array of "chars" i.e. a string.
So just say I wish to allocate memory for an array of 20 "word"
elements, each word element has a string of 30 chars. How would I do
this?
I tried the code below but i keep getting errors.. please help me!
array *array1;
int element, number;
array1 = malloc(1); // Allocating memory to the array
number = 20; // 20 word elements in the array
array1->wordArray = malloc(number * sizeof *array->wordArray);
element = 0;
while (element < number)
{
array1->wordArray[element].string = malloc(30);
element++;
}
Thank you all so much for your help!
mike79
I am having problems properly malloc'ing an array. The problem is, I
have a structure called "array" which contains 2 elements, "int
arraySize" (how many elements are in the array) and "wordArray" (the
actual array itself).
The "word structure" consists of 2 elements, "int occurrence" (the
number of times that particular word occurs in say a sentence, and
"char *string" (the actual word itself).
So the two structures look like this:
typedef struct words
{
int occurrence;
char *string;
}word;
typedef struct arrays
{
int arraySize;
word *wordArray;
}array;
So what I am trying to do is create 1 structure of "array" to keep
track of the number of elements(words) contained in that array, and
the array itself.
The "array" structure contains an array of "word" structures. And the
"word" structure contains an array of "chars" i.e. a string.
So just say I wish to allocate memory for an array of 20 "word"
elements, each word element has a string of 30 chars. How would I do
this?
I tried the code below but i keep getting errors.. please help me!
array *array1;
int element, number;
array1 = malloc(1); // Allocating memory to the array
number = 20; // 20 word elements in the array
array1->wordArray = malloc(number * sizeof *array->wordArray);
element = 0;
while (element < number)
{
array1->wordArray[element].string = malloc(30);
element++;
}
Thank you all so much for your help!
mike79