Pergunta

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));
}
Foi útil?

Solução

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]);

Outras dicas

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
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top