简体   繁体   English

使用 malloc 动态创建字符串数组

[英]Dynamically create an array of strings with malloc

I am trying to create an array of strings in C using malloc .我正在尝试使用malloc在 C 中创建一个字符串数组。 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,但是你清楚地为一个特定的字符串分配了内存,你可以释放一块内存而不释放整个“字符串数组”

char **orderIds;

orderIds = malloc(variableNumberOfElements * sizeof(char*));

for(int i = 0; i < variableNumberOfElements; i++) {
  orderIds[i] = malloc((ID_LEN + 1) * sizeof(char));
  strcpy(orderIds[i], your_string[i]);
}

Given that your strings are all fixed-length (presumably at compile-time?), you can do the following:鉴于您的字符串都是固定长度的(大概是在编译时?),您可以执行以下操作:

char (*orderedIds)[ID_LEN+1]
    = malloc(variableNumberOfElements * sizeof(*orderedIds));

// Clear-up
free(orderedIds);

A more cumbersome, but more general, solution, is to assign an array of pointers, and psuedo-initialising them to point at elements of a raw backing array:一个更麻烦但更通用的解决方案是分配一个指针数组,并伪初始化它们以指向原始支持数组的元素:

char *raw = malloc(variableNumberOfElements * (ID_LEN + 1));
char **orderedIds = malloc(sizeof(*orderedIds) * variableNumberOfElements);

// Set each pointer to the start of its corresponding section of the raw buffer.
for (i = 0; i < variableNumberOfElements; i++)
{
    orderedIds[i] = &raw[i * (ID_LEN+1)];
}

...

// Clear-up pointer array
free(orderedIds);
// Clear-up raw array
free(raw);

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

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

..

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM