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

问题描述 投票:17回答:4

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

c arrays malloc
4个回答
16
投票

据我从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-correctity规则。

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

const  char** new_array;      

从消息限制中删除“ array_pointers_of_strings”声明中的const


6
投票

此:

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)), ...;

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?因为Calloc是C标准库中适用于该工作的函数,所以:

“ calloc()函数为每个大小为字节的nmemb元素数组分配内存,并返回指向已分配内存的指针”

。 (来源:here

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

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);}

希望它对你们有用!

© www.soinside.com 2019 - 2024. All rights reserved.