I started to read a few articles about pointers in C and I've got one example that I don't understand.
The example is from here: http://en.wikibooks.org/wiki/C_Programming/Pointers_and_arrays
Here it is:
Let's look at a slightly different problem. We want to have a two dimensional array, but we don't need to have all the rows the same length. What we do is declare an array of pointers. The second line below declares A as an array of pointers. Each pointer points to a float. Here's some applicable code:
float linearA[30];
float *A[6];
A[0] = linearA; /* 5 - 0 = 5 elements in row */
A[1] = linearA + 5; /* 11 - 5 = 6 elements in row */
A[2] = linearA + 11; /* 15 - 11 = 4 elements in row */
A[3] = linearA + 15; /* 21 - 15 = 6 elements */
A[4] = linearA + 21; /* 25 - 21 = 4 elements */
A[5] = linearA + 25; /* 30 - 25 = 5 elements */
A[3][2] = 3.66; /* assigns 3.66 to linearA[17]; */
A[3][-3] = 1.44; /* refers to linearA[12];
negative indices are sometimes useful.
But avoid using them as much as possible. */
My question is why A[0]
is a pointer only to five elements and not to ALL of linearA
, since the name of an array is a pointer to its first member.
And A[1] = linearA + 5;
is 6 elements in a row -- for the same reason? Isn't A[1]
supposed to be a pointer to the 6th member of linearA
?
Can someone explain where is my mistake?
A pointer is a variable whose value is the address of another variable of the same type. The value of the variable that the pointer points to by dereferencing using the * operator. The different types of pointers are void, null, dangling, wild, near, far, huge. A pointer can be typecasted to different data types.
Pointers are used to store and manage the addresses of dynamically allocated blocks of memory. Such blocks are used to store data objects or arrays of objects. Most structured and object-oriented languages provide an area of memory, called the heap or free store, from which objects are dynamically allocated.
Except in a few exceptions, in C an array name is converted to a pointer to the first element of the array. linearA
is an array 30 of float
and in the expression:
A[0] = linearA;
it is converted to a pointer to float
.
A
is an array 6 of pointer to float
. The element of A
are of type pointer to float
. So A[0]
is a pointer to float
and not a pointer to an array.
And A[i][j]
in C is equivalent to *(A[i] + j)
so A[i][j]
is a float
(dereferencing a pointer to float
yields a float
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With