我在 C 中有这个结构 示例:
typedef struct
{
const char * array_pointers_of_strings [ 30 ];
// etc.
} message;
我需要将此 array_pointers_of_strings 复制到新数组以对字符串进行排序。我只需要复制地址。
while ( i < 30 )
{
new_array [i] = new_message->array_pointers_of_strings [i];
// I need only copy adress of strings
}
我的问题是:如何通过 malloc() 为字符串地址分配 new_array [i]?
最佳答案
正如我从 while 循环中的赋值语句中了解到的那样,我认为您需要的是字符串数组:
char** new_array;
new_array = malloc(30 * sizeof(char*)); // ignore casting malloc
注意:通过在 while 循环中执行 =
,如下所示:
new_array [i] = new_message->array_pointers_of_strings [i];
你只是在分配字符串地址(它不是深拷贝),但因为你也在写“只有字符串地址”所以我认为这就是你想要的。
编辑: 警告 “赋值从指针目标类型中丢弃限定符”
您收到此警告是因为您将 const char*
分配给 char*
,这将违反 const 正确性规则。
您应该像这样声明您的 new_array:
const char** new_array;
或从消息结构中删除“array_pointers_of_strings”声明中的const
。
关于c - 如何在 C 中通过 malloc 为字符串分配指针数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15686890/