user1357576
user1357576

Reputation: 409

Clarification about copying an array by referencing a pointer

So I have this array in a header file like this:

// header.h
static const unsigned int array1[]={0x00,0x01,0x02,0x03};

And:

// file.c
main()
{
     unsigned int *ptrToArray;

     ptrArray = &array1[0];
 }

Correct me if I am wrong. I assume: to find the number of bytes of array elements, instead of sizeof(array1) the equivalent will be sizeof(*ptrArray), right?

And to access the elements of the array, instead of array[i], it will now be:

Upvotes: 1

Views: 73

Answers (4)

pb2q
pb2q

Reputation: 59637

sizeof won't behave in the same way for your pointer: your example will give you the size of the datatype: unsigned int.

And while you can use pointer arithmetic to reference elements through ptrArray, you can just as well use standard array dereferencing: ptrArray[0], ptrArrray[1], ... and in most cases you're better off doing so.

Upvotes: 0

Ed Swangren
Ed Swangren

Reputation: 124732

A pointer is not an array, and an array is not a pointer. An array can decay into a pointer when convenient, but it is still a complete type.

So, the type of *someIntPointer is int, not an array, even if that pointer happens to point to the first element in an array. sizeof(someArray) works as you would expect because it knows that the type is actually an array.

Upvotes: 2

Wug
Wug

Reputation: 13196

Sizeof will return the size of the pointer for regular pointer types. If you sizeof a dereferenced pointer type, you will get the size of the element (i.e. sizeof(unsigned int)). You will need to either keep track of the number of elements in the array yourself, or use sizeof on the array declaration.

As for accessing, you could do it that way, but you can just use the bracket notation as you would with a normal array.

Arrays are a special class of pointer. The compiler knows when to treat an array as an array and when to treat it as a pointer: that's how it knows how big an array is, but you can still pass it to functions that expect an array (when you do this, you get a pointer to the first element). The same does not work in reverse however: The compiler will never treat a pointer declared as a pointer as an array.

By the way, [] just simplifies to pointer arithmetic. You can add a pointer to an int, but you can also add an int to a pointer. You can thus (but probably shouldn't) do weird things like 1[ptrArray]

Upvotes: -2

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272667

The type of *ptrToArray is int, therefore sizeof(*ptrToArray) is the same as sizeof(int). So it won't tell you anything about the number of elements in array1.

Whilst you can write *(ptrArray+1), etc., you should just write ptrToArray[1]!

Upvotes: 4

Related Questions