如何为10个字符的字符串数组分配内存

时间:2015-11-15 05:41:28

标签: c

我有以下变量称为行,并希望为变量的10个实例分配内存。

Delay for claiming slot 0 is 0
Delay for claiming slot 1 is 0
Delay for claiming slot 2 is 0
Delay for claiming slot 3 is 0
Delay for claiming slot 4 is 0
Delay for claiming slot 5 is 0
Delay for claiming slot 6 is 0
Delay for claiming slot 7 is 0
Received message with sequence 0. EndOfBatch = true
Delay for claiming slot 8 is 505
Received message with sequence 1. EndOfBatch = false
Received message with sequence 2. EndOfBatch = false
Received message with sequence 3. EndOfBatch = false
Received message with sequence 4. EndOfBatch = false
Received message with sequence 5. EndOfBatch = false
Received message with sequence 6. EndOfBatch = false
Received message with sequence 7. EndOfBatch = true
Delay for claiming slot 9 is 3519
Received message with sequence 8. EndOfBatch = true
Received message with sequence 9. EndOfBatch = true

它不起作用,我不知道问题是否与声明或分配有关。提前谢谢。

3 个答案:

答案 0 :(得分:3)

 lines = malloc(10*sizeof(*lines));

会做到这一点。实际上,

的一般技术
 pointer = malloc(number_needed * sizeof(*pointer));

是使用malloc()时减少错误的一般方法,因为sizeof(*pointer)总是给出所需元素的大小。

然而,这是一种C技术(正如你的问题实际上是C,而不是C ++)。

在C ++中,你可以在C ++中做得更好

 std::string lines[10];

或(如果您希望选项在运行时动态更改行数)

 std::vector<std::string> lines(10);

std::stringstd::vector分别在标准标题<string><vector>中声明。

答案 1 :(得分:2)

char (*lines)[30]lines声明为指向30 char数组的指针。如果要分配此类数组的10个元素,则应按如下方式进行分配:

char (*lines)[30] = malloc( 10 * sizeof( *lines ) );

答案 2 :(得分:0)

我猜你想要分配10个arrarys,每个arrarys长度为30个字符,只有一个malloc()函数调用。您必须打算使用变量&#39;行&#39;作为分配内存的索引,因为分配的内存实际上是一个10 * 30 = 300个字符的数组。

您需要检查的是malloc()函数的类型转换。变量&#39;行&#39;是一个指向30个字符的指针,而在malloc()之前的类型转换是灌输一个字符。

lines = malloc(10 * sizeof(char) * 30);