简体   繁体   中英

How to allocate memory for an array of pointers to a char in c

I've working on a program in c and got stuck with allocating memory for an array of pointers to char, I will need to sort this array in the future. Array should store chars in it and then I want to sort these chars in alphabetical order.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>


typedef struct
{
    char collection[50]; 
} data_col;

int main(int argc, char const *argv[])
{
    data_col * array [10] = malloc(sizeof(data_col));

    for (size_t i = 0; i < 10; i++)
    {
        scanf("%c", &array[i]->group);
    }

    return 0;
}

You can allocate the memory for your 10 pointers by simply writing this:

data_col * array[10];

If you put this at the top level of your program, it is a global variable and you can use it any time during your program, and the pointers are all initialized to null pointers for you.

If you put it in a function, then the memory will be deallocated/freed when the function returns. The pointers will start in an uninitialized/undefined state.

Note that you still need to initialize each of these 10 pointers before you can use them for anything. You might choose to use malloc to allocate the space for the individual data_col objects, or you could make an array of data_col objects and have your pointers pointing into that array. However, your question wasn't about that; your question is simply about how to allocate memory for the array of pointers , and the code I showed above succeeds in allocating that memory for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM