Reputation: 174
I've written a C program for showing the values of an array using pointer. Here's the code :
#include <stdio.h>
int main()
{
int a[] = {1, 1, 1, 1, 1};
int *ptr = a;
for (int i = 0 ; i < 5; i++)
printf("%d ", *ptr++);
printf("%d", *ptr);
}
As you can see after terminating the loop, the pointer holds the memory address of a value out of the array. As it i.e. the last output is not initialized, it should be a garbage value. But, every time it is showing 5 which is the size of the array. Then, I thought the next memory address of allocated memory for array contains the size of array. But, this is not happening with double type array.
Output for int array : 1 1 1 1 1 5
Output for double array : 1.000000 1.000000 1.000000 1.000000 1.000000 1.000000 0.000000
Will anyone explain the output?
Upvotes: 1
Views: 266
Reputation: 123558
C does not store any array metadata (including array length) anywhere, either at the beginning or the end of the array. In the case of the integer array, the most likely explanation for the output is that the memory used by the variable i
immediately follows the last element of the array, like so:
+---+
a: | 1 | a[0]
+---+
| 1 | a[1]
+---+
| 1 | a[2]
+---+
| 1 | a[3]
+---+
| 1 | a[4]
+---+
i: | 5 | a[5]
+---+
However, you cannot rely on this behavior being consistent, as you saw with changing the array type to double
.
Attempting to read the value contained in the element one past the end of the array results in undefined behavior. Chapter and (truncated) verse:
6.5.6 Additive operators
...
8 When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand...If the result points one past the last element of the array object, it shall not be used as the operand of a unary*
operator that is evaluated.
For giggles, I compiled your code on my system at work, and I get the following output:
1 1 1 1 1 0
This really is just an artifact of how the compiler lays objects out in memory for this particular program.
Upvotes: 3
Reputation: 53016
What you do invokes Undefined Behavior.
It's simple a coincidence and probably just the value of i
, print the address of i
and check. But be careful, it will not always be that way. Just declare a new variable in the program and it might change.
In the case of double
it doesn't work because the address after the array no longer matches the address of i
. It's what I mean when I say Be careful.
Upvotes: 2
Reputation: 1881
This is just a value from memory in this address. You should never access memory which is not allocated by you (In this case you are accessing 6th element, but you have declared just 5). This may lead to segmentation fault is some cases.
Upvotes: 6