动态地创建使用malloc字符串数组 [英] Dynamically create an array of strings with malloc

查看:371
本文介绍了动态地创建使用malloc字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个使用的malloc 在C字符串数组。该阵列将持有可以在运行时改变串的数目,但是弦线的长度将始终是一致

我尝试这个(见下文),但我有麻烦,在正确的方向任何提示将更加AP preciated!

 的#define ID_LEN 5
字符* orderedIds;
INT I;
INT variableNumberOfElements = 5; / *硬codeD这里* /orderedIds = malloc的(variableNumberOfElements *(ID_LEN + 1));

最后,我希望能够使用数组来做到这一点:

 的strcpy(orderedIds [0],字符串1);
的strcpy(orderedIds [1],字符串2);
/ *等* /


解决方案

您应该指定字符数组的指针,然后,对每个指针分配足够的内存字符串:

 的char ** orderedIds;orderedIds =的malloc(variableNumberOfElements * sizeof的(字符*));
的for(int i = 0; I< variableNumberOfElements;我++)
    orderedIds [I] =的malloc((ID_LEN + 1)* sizeof的(炭)); //是的,我知道的sizeof(char)的是1,但要清楚...

似乎是一个很好的方式给我。虽然你执行许多mallocs,你清楚地分配内存的特定字符串,并且可以释放内存的一个块而不释放整个字符串数组

I am trying to create an array of strings in C using malloc. The number of strings that the array will hold can change at run time, but the length of the strings will always be consistent.

I've attempted this (see below), but am having trouble, any tips in the right direction will be much appreciated!

#define ID_LEN 5
char *orderedIds;
int i;
int variableNumberOfElements = 5; /* Hard coded here */

orderedIds = malloc(variableNumberOfElements * (ID_LEN + 1));

Ultimately I want to be able to use the array to do this:

strcpy(orderedIds[0], string1);
strcpy(orderedIds[1], string2);
/* etc */

解决方案

You should assign an array of char pointers, and then, for each pointer assign enough memory for the string:

char **orderedIds;

orderedIds = malloc(variableNumberOfElements * sizeof(char*));
for (int i = 0; i < variableNumberOfElements; i++)
    orderedIds[i] = malloc((ID_LEN+1) * sizeof(char)); // yeah, I know sizeof(char) is 1, but to make it clear...

Seems like a good way to me. Although you perform many mallocs, you clearly assign memory for a specific string, and you can free one block of memory without freeing the whole "string array"

这篇关于动态地创建使用malloc字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆