简体   繁体   English

如何将 int 添加到 int**?

[英]How do I add int to a int**?

I'm coding in C.我正在用 C 编码。

I'm receiving the following variable as an argument int** list .我收到以下变量作为参数int** list

I'm allocating the memory like this :我像这样分配内存:

list = (int **)malloc(sizeof(int) * numberOfItems);

I'm looping through another list and I want to add an integer to the list variable.我正在遍历另一个列表,我想向list变量添加一个整数。 Here's my code :这是我的代码:

*list[i] = i;

I'm getting the following error :我收到以下错误:

[1]    18404 segmentation fault  program

What have I done wrong ?我做错了什么?

Although necessary in C++, it is not necessary ( nor suggested ) to cast the return of [m][c][re]alloc in ANSI C. So your first statement should be: (note the argument of the sizeof statement...)尽管在 C++ 中是必需的,但没有必要( 也不建议)在 ANSI C 中[m][c][re]alloc的返回值。所以你的第一条语句应该是:(注意sizeof语句的参数...... )

list = malloc(sizeof(* list) * numberOfRows);//create the first level of array of pointers

Then loop through, as you have indicated in your post, allocating memory for each of the locations created in the first statement:然后循环遍历,正如您在帖子中指出的那样,为第一个语句中创建的每个位置分配内存:

for(i=0;i<numOfRows;i++)
{
    list[i] = malloc(sizeof(int));
}

Note: in acknowledgement of @MM's comment, although it is not necessary, or generally recommended (read link above) to cast return of malloc in C, the example code you provide in your original post provides one good illustration where using the cast spotlights and exposes immediately the possibility of a bug.注意:感谢@MM 的评论,虽然没有必要或通常建议(阅读上面的链接)在 C 中转换 malloc 的返回值,但您在原始帖子中提供的示例代码提供了一个很好的说明,其中使用了投射聚光灯和立即暴露出错误的可能性。 ie that the cast: (int **) does not match the argument of sizeof : int .即 cast: (int **)sizeof : int的参数不匹配。

As @FiddlingBits pointed out, my method of allocation was incorrect.正如@FiddlingBits 指出的那样,我的分配方法不正确。

Here's the fix :这是修复:

int *workList = (int *)malloc(sizeof(int) * hardworkingDwarfCount);
list = &workList;

And :和 :

workList[i] = i;

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

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