How to play with pointers in C

Donotalo
322K views

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

The sizeof operator takes a parameter and returns the size of the parameter in bytes. Following example prints the size of an array with 3 elements, each is a 32 bit integer:

#define ARRAY_SIZE 3

int32_t arr[ARRAY_SIZE] = { 0 };

size_t size = sizeof(arr);
printf("Array size %d bytes\n", size);

The return type of sizeof operator is size_t which is an integer. The example above will convey the message that the array size is 12 bytes (3 integers, 4 bytes each).

Now consider the following program:

You'll notice that the sizes are different in main() and print_array_size() even though it appears that the same 12 byte array arr is passed to the print_array_size() function. Based on compiler settings, you could also see warning for using sizeof operator on parameter parr because parr is declared as array.

What happens is when an array is passed to a function as parameter, it is converted to a pointer to the first element of the array. In the example above, parr is indeed a pointer to arr[0] even though array syntax ([]) is used.

Hence, sizeof(parr) returns the size of a pointer on the platform. The code above will work the same way if the function prototype is declared as follows:

void print_array_size(const int32_t* parr)

An array can be passed to a function through pointer. Using the parameter which is a pointer to the array the array elements can be modified:

In the above example the character array or C string str is passed to string_to_upper() function using parameter pstr which becomes pointer the the first character of the array. Using pstr the whole array is modified. Then str is printed in main() and the modifications made in string_to_upper() is observed.

Open Source Your Knowledge: become a Contributor and help others learn. Create New Content