简体   繁体   English

如何为 c 中的 char 指针数组分配 memory

[英]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.我正在处理 c 中的一个程序,并被困在为一个指向 char 的指针数组分配 memory 中,我将来需要对这个数组进行排序。 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:您可以通过简单地编写以下代码为您的 10 个指针分配 memory:

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.如果你把它放在你程序的顶层,它是一个全局变量,你可以在你的程序中的任何时候使用它,并且指针都为你初始化为 null 指针。

If you put it in a function, then the memory will be deallocated/freed when the function returns.如果将其放入 function 中,则 memory 将在 function 返回时被释放/释放。 The pointers will start in an uninitialized/undefined state.指针将从未初始化/未定义的 state 开始。

Note that you still need to initialize each of these 10 pointers before you can use them for anything.请注意,您仍然需要初始化这 10 个指针中的每一个,然后才能将它们用于任何事情。 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.您可以选择使用malloc为各个data_col对象分配空间,或者您可以创建一个data_col对象数组并将指针指向该数组。 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.您的问题只是关于如何为指针数组分配 memory ,我上面显示的代码成功地为您分配了 memory 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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