如何在C语言中使用malloc为字符串数组分配指针?

19

我在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]?

4个回答

19

根据您的任务陈述和while循环,我认为您需要一个字符串数组:

char** new_array;
new_array = malloc(30 * sizeof(char*)); // ignore casting malloc

注意:在下面的 while 循环中使用 =

new_array [i] = new_message->array_pointers_of_strings [i];

你只是在分配字符串的地址(这不是深拷贝),但因为你也写了“only address of strings”,所以我想这就是你想要的东西。

编辑:警告:“assignment discards qualifiers from pointer target type”

你收到此警告是因为你正在将 const char* 分配给 char*,这会违反 const-correctness 的规则。

你应该像这样声明你的 new_array:

const  char** new_array;      

或者在消息结构中的 'array_pointers_of_strings' 声明中移除 const


是的,我需要这个,但是 new_array[i] = new_message->array_pointers_of_strings[i]; 这一行有问题 O_o 我的编译器 gcc 给我写了这个警告:assgiment discards qualifiers from pointer target type。 - user1779502
如果我在 malloc(30 * sizeof(char*)) 中使用双精度变量而不是数字30,那么 new_array [i] 语法将无法工作。那么如何访问元素呢? - hpaknia

7

This:

char** p = malloc(30 * sizeof(char*));

该代码将分配一个足够大的缓冲区来存储30个指向char的指针(或者说是字符串指针),并将其地址赋值给p

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


原来的答案...

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

message msg1, msg2, ...;

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

message *pmsg1 = malloc(sizeof(message)), *pmsg2 = malloc(sizeof(message)), ...;

不,我有一个名为new_message的指针,其中包含字符串指针数组。我需要通过malloc为30个地址字符串分配char数组。我不知道如何为复制字符串的地址分配新数组... - user1779502

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

#define ARRAY_LEN 2
typedef struct
{
    char * string_array [ ARRAY_LEN ];
} message;

int main() {
    int i;
    message message;
    message.string_array[0] = "hello";
    message.string_array[1] = "world";
    for (i=0; i < ARRAY_LEN; ++i ) {
        printf("%d %s\n",i, message.string_array[i]);
    }

    char ** new_message = (char **)malloc(sizeof(char*) * ARRAY_LEN);
    for (i=0; i < ARRAY_LEN; ++i ) {
        new_message[i] = message.string_array[i];
    }
    for (i=0; i < ARRAY_LEN; ++i ) {
        printf("%d %s\n",i, new_message[i]);
    }
}

1

你是否必须使用Malloc?因为C Standard Library中的Calloc函数可以完成这项工作:

"calloc()函数为nmemb个大小为size字节的元素数组分配内存,并返回指向分配内存的指针"。(来源:这里

我正在创建一个哈希表,它有一个指向节点的指针数组,一个简单的方法是这样的:

hash_table_t *hash_table_create(unsigned long int size){
hash_table_t *ptr = NULL;

ptr = malloc(sizeof(hash_table_t) * 1);
if (ptr == NULL)
    return (NULL);

ptr->array = calloc(size, sizeof(hash_node_t *)); #HERE
if (ptr->array == NULL)
    return (NULL);
ptr->size = size;
return (ptr);}

希望对你们有用!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接