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

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

问题描述

我正在尝试使用 malloc 在 C 中创建一个字符串数组.数组将保存的字符串数量可以在运行时更改,但字符串的长度将始终保持一致.

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...

对我来说似乎是一个好方法.虽然你执行了很多 malloc,但是你明确地为一个特定的字符串分配了内存,你可以释放一块内存而不用释放整个字符串数组"

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天全站免登陆