I have 2 structs in my program.
linked list of id's, and a WORD
typedef struct related
{
int id;
struct related* next;
} RELATED;
typedef struct word
{
int id;
char name[NAME_LEN];
RELATED *related;
} WORD;
i want to hold an array of WORD's and i want it to be dynamic.
I have 2 pointers to words:
WORD* word1;
WORD* word2;
with values.
when i am tryin to dynamically allocate it in this way:
WORD** arr = (WORD**)malloc(sizeof(WORD*)*10) // to hold 10 words
and trying to add a word to an array, the first one is added properly, but the second one run over the first one:
arr[0] = word1;
arr[1] = word2;
when i am defining the array this way:
WORD* arr[40];
the same add of words works just fine
arr[0] = word1;
arr[1] = word2;
can't quite find the right way of this dynamic allocation.. thnx for help!
-
Seems to work fine for me? (Yes, not free'ing memory, fine for this purpose though)Kep– Kep2014年01月10日 00:46:29 +00:00Commented Jan 10, 2014 at 0:46
-
It should work fine, can you share your program code?Cool Goose– Cool Goose2014年01月10日 04:35:02 +00:00Commented Jan 10, 2014 at 4:35
3 Answers 3
Rather than
// arr as pointer to pointer to WORDS
WORDS** arr = (WORDS**)malloc(sizeof(WORDS*)*10);
Allocate
// arr as pointer to WORDS
WORDS* arr = malloc(sizeof(*arr) * 10); // WORDS *, not WORDS **
- C gibberish ↔ English may be useful.
- Casting the result of
malloc()is discouraged in C. - Consider the
type *p = malloc(sizeof(*p) * N);style. Easier to maintain and less error prone IMO.
2 Comments
malloc() holds 10 pointers to WORDS. Further, Are you simple wanting to copy pointers word1, word2 or the date they point to?I couldn't find any issue with malloc() and using pointer to pointer of WORD as array. One thing I can point out that, you have not allocated memory for word1 and word2 they hold a garbage address. Same garbage address is being assigned to arr[0] and arr[1]. If you upload complete code, it will help in finding out exact problem.
Comments
You can use following code snippet for dynamic memory allocation for 2D array :
Let 'm' and 'n' are dimensions of an array .
WORDS** arr = (WORDS**)malloc(sizeof(WORDS*)*m);
for(int i = 0 ; i < m ; i++)
{
for(int j = 0 ; j < n ; j++)
{
arr[i] = (WORDS*)malloc(sizeof(WORDS)*n);
}
}