문제

I am trying to point a pointer to a calloc array. For some reason, when I reach the second element the program force quits. The first element prints out and works fine. Here is an example of my code just trying to print out all the elements through a second pointer:

integerArray = (int*)calloc(totalNum, sizeof(int));

if(integerArray == NULL)
{
    printf("ERROR! Number entered is invalid.");
    exit(1);
}

collectNumbers(totalNum, integerArray);

arrayAscending = &integerArray;
arrayDescending = &integerArray;

for(i = 0; i < totalNum; i++)
{
    printf("%3d", **(arrayAscending + i));
}
도움이 되었습니까?

해결책

The problem is here:

printf("%3d", **(arrayAscending + i));

You are incrementing a pointer to pointer.

In accordance to the code that I see here, it supposed to be the following:

printf("%3d", *((*arrayAscending) + i)));

The first of all you should dereference the arrayAscending in order to get the pointer integerArray value and only after this increment it if you do not want use the indexing.

You can also write as follows:

printf("%3d",(*ayyarAscending)[i]);

But actually more simple is just using indexing:

printf("%3d", integerArray[i]);

다른 팁

arrayAscending = &integerArray;   // these point to the int*, they don't get the value...
arrayDescending = &integerArray;

for(i = 0; i < totalNum; i++)
{
    printf("%3d", integerArray[i]);  // FIXED
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top