我如何动态地分配在C字符串数组? [英] How do I dynamically allocate an array of strings in C?

查看:97
本文介绍了我如何动态地分配在C字符串数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个变种的项目名为totalstrings的数量,一个名为字符串大小无功就是每个项目的字符串大小,我该如何动态分配称为阵阵?

If I have the number of items in a var called "totalstrings" and a var called "string size" that is the string size of each item, how do I dynamically allocate an array called "array?"

这是C,而不是C ++。

This is an array of strings in C, not C++.

谢谢!

推荐答案

请注意:我的例子不是检查从malloc()函数返回NULL ...你真的应该做,虽然;如果您尝试使用NULL指针,你会崩溃。

NOTE: My examples are not checking for NULL returns from malloc()... you really should do that though; you will crash if you try to use a NULL pointer.

首先,你必须创建字符指针的每一个字符串(字符*)数组,其中:

First you have to create an array of char pointers, one for each string (char *):

的char **数组=的malloc(totalstrings * sizeof的(字符*));

接下来,您需要为每个字符串分配空间:

Next you need to allocate space for each string:

int i;
for (i = 0; i < totalstrings; ++i) {
    array[i] = (char *)malloc(stringsize+1);
}

当你使用数组做,你一定要记得免费()每次你分配的指针。也就是说,通过数组调用免费()在它的每个元素,最后免费(阵列)作为循环好。

When you're done using the array, you must remember to free() each of the pointers you've allocated. That is, loop through the array calling free() on each of its elements, and finally free(array) as well.

这篇关于我如何动态地分配在C字符串数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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