chrismason954 chrismason954 - 1 month ago 11
C Question

C Program with Pointer Increment False Values

I'm wondering if anyone can help me with the following C Program I am making. The code simply creates a pointer, which is then assigned the address of an integer array. From there, the pointer is given a value and is then incremented.
The output displays the array name, the array address and the array value. The output works as expected, except the last item in the array has increased by 5, rather than one.

The code is shown below :

#include <stdio.h>

main()
{
int numar[4]; //integer array
int x; //value for loop
int *p; //pointer
p=numar; //'point' p to address of numar array (no & necessary as arrays are pointers)
for(x=0;x<5;x++) //loop 0-4
{
*p=x; //assign the value of the first item in array to x
p++; //increment pointer for next iteration
}
for(x=0;x<5;x++) //loop 0-4
{
//display output of array name, array location and array value
printf("array[%d] is at address %p with value %d\n", x,&numar[x],numar[x]);
}
return 0;
}


The output of the above code is shown below :

array[0] is at address 0061FF18 with value 0
array[1] is at address 0061FF1C with value 1
array[2] is at address 0061FF20 with value 2
array[3] is at address 0061FF24 with value 3
array[4] is at address 0061FF28 with value 8


As you can see, the desired value for array[4] should be 4, but it is instead 8.

Any help would be greatly appreciated.

Many Thanks,

Answer

In order to make your code compile, I had to make one change: I added 'int' before 'main', so that the main function could correctly return 0.

The problem is that you have created an integer array of size 4, but you want it to contain 5 items.

int numar[4];

Means that your array is defined for 4 elements:

numar[0]
numar[1]
numar[2]
numar[3]

Therefore,

numar[4]

is undefined.

To fix this, make your array one size larger:

int numar[5];

The output I get is:

array[0] is at address 0x7fff557f0730 with value 0
array[1] is at address 0x7fff557f0734 with value 1
array[2] is at address 0x7fff557f0738 with value 2
array[3] is at address 0x7fff557f073c with value 3
array[4] is at address 0x7fff557f0740 with value 4