开发者

malloc allocation for char **foobar or char *foobar[], how to proceed? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
开发者_运维知识库

Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist

Closed 9 years ago.

Improve this question

I would like to know how to allocate memory when you have an array of words (char **words or even char *words[].


You can try this:

    char **words;
    words = malloc(sizeof(char)*MAX_WORD_SIZE*MAX_NUM_WORDS);

    if (words == 0)
    {
        printf("ERROR: Out of memory\n");
        return 1;
    }
            .... <use words>
    free(words);

where MAX_WORD_SIZE is the maximum length (minus the "\0" terminating character) that your strings may have; and MAX_NUM_WORDS the maximum number of words you would like to manage.

The code above will allocate the memory to hold all the words that you would like to manage.

You could also use calloc, which has the big advantage of setting the memory to "0", which is very useful when dealing with strings:

    words = (char**)calloc(MAX_NUM_WORDS, sizeof(char)*MAX_WORD_SIZE);


#include <stdlib.h>

// void *calloc(size_t nelem, size_t elsize);

// ...
return calloc(n, sizeof(char *));

Using calloc ensures that all your pointers start out as null rather than as uninitialized.


You allocate memory for an array of pointers.

char** words = malloc(num_of_elements * sizeof(char*));

Then, if you have to copy the strings, you allocate memory for each of the strings and put the malloced addresses to this array.

If the strings won't be modified you can play tricks to lower memory consumption by allocating a continuous range and put the strings there, but basically that's it.


Firstly, is it a square allocation? i.e. are there the same number of elements in each row?

If they are, then you can use the simple:

char **words = calloc(rows * columns * sizeof(char *))

and then accessing each item@ COL,ROW is a case of:

words[ROW * columns + COL]

if it's not symmetric, i.e. you have a variable number of columns per row, then you have to use something a little more complicated. In the case you have an array cols[ROWS], which contains the size of each column on a row by row basis, then you need to:

char **words = calloc(ROWS, sizeof(char **));
for (int i = 0; i < ROWS; i++) {
    words[i] = calloc(cols[i], sizeof(char *));
}

You would access each item by:

words[ROW][COL]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜