简体   繁体   中英

How do I add int to a int**?

I'm coding in C.

I'm receiving the following variable as an argument 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. 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...)

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. ie that the cast: (int **) does not match the argument of sizeof : int .

As @FiddlingBits pointed out, my method of allocation was incorrect.

Here's the fix :

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

And :

workList[i] = i;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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