如何在C中通过malloc为字符串分配指针数组?

use*_*502 16 c arrays malloc

我在C中有这个结构示例:

typedef struct 
{
    const char * array_pointers_of_strings [ 30 ];
    // etc.
} message;
Run Code Online (Sandbox Code Playgroud)

我需要将此array_pointers_of_strings复制到新数组以进行排序字符串.我只需要复制地址.

while ( i < 30 )
{
   new_array [i] = new_message->array_pointers_of_strings [i]; 
   // I need only copy adress of strings
}
Run Code Online (Sandbox Code Playgroud)

我的问题是:如何通过malloc()分配new_array [i]仅用于字符串的地址?

Gri*_*han 14

我可以从while循环中的赋值语句中理解,我认为你需要字符串数组:

char** new_array;
new_array = malloc(30 * sizeof(char*)); // ignore casting malloc
Run Code Online (Sandbox Code Playgroud)

注意:通过=while循环执行如下:

new_array [i] = new_message->array_pointers_of_strings [i];
Run Code Online (Sandbox Code Playgroud)

你只是分配字符串的地址(它不是深拷贝),但因为你也在写" 只有字符串的地址 "所以我认为这就是你想要的.

编辑: waring "赋值从指针目标类型中丢弃限定符"

因为你分配你得到这样的警告const char*,以char* 可能违反常量,正确的规则.

你应该声明你的new_array:

const  char** new_array;      
Run Code Online (Sandbox Code Playgroud)

或者const从message stricture中删除'array_pointers_of_strings'的声明.


Ale*_*nze 5

这个:

char** p = malloc(30 * sizeof(char*));
Run Code Online (Sandbox Code Playgroud)

将分配一个足够大的缓冲区来保存30个指针char(如果你愿意,还可以指定字符串指针)并分配给p它的地址.

p[0]是指针0,p[1]是指针1,......,p[29]是指针29.


老答案......

如果我正确理解了这个问题,你可以通过简单地声明类型的变量来创建一个固定数量的问题message:

message msg1, msg2, ...;
Run Code Online (Sandbox Code Playgroud)

或者你可以动态分配它们:

message *pmsg1 = malloc(sizeof(message)), *pmsg2 = malloc(sizeof(message)), ...;
Run Code Online (Sandbox Code Playgroud)