Pointers and Arrays
In this section we will consider the relationship between pointers and arrays as well as some of the implications this may have when you write code.
In the previous chapter, we introduced the string.h library. If you look at the documentation of this library you will notice that the prototypes of the functions are listed like this:
size_t strlen(const char* str );
Notice that the string that the data type here is const char* even though str is a null terminated character array. This implies that if you have an array, you can pass it into a function that accepts pointers.
This is actually true.... because the name of an array is a pointer to the first element. In otherwords, if I were to declare an array as follows:
int myArray[10];
The name of this array is myArray. this variable resolves to the address of the first element of the array.
Therefore, if I were to write a function that accepts an array as its parameter like this:
void someFunction(int array[], int used);
I can also write the prototype like this:
void someFunction(int* array, int used);
for the most part, the two are interchangeable
sizeof()
The sizeof() operator calculates the size (number of bites) of the types/variables given to it. It is not a function, even though it looks like one. The main thing to note about the sizeof operator is how it operates on arrays. In particular how it operates on arrays that were passed to functions.
Consider the following program.... what is the output?
#include <stdio.h>
void checksizeof(char mystr[]);
int main(void)
{
char mystr[100];
int len = sizeof(mystr);
printf("main(): sizeof(mystr) = %d\n",len);
checksizeof(mystr);
}
void checksizeof(char mystr[])
{
int len = sizeof(mystr);
printf("in checksizeof(): sizeof(mystr) = %d\n",len);
}
firstly, depending on your compiler you may have gotten a warning when you tried to compile the above program. This is because inside the checksizeof() function mystr is essentially a pointer. it holds the starting address of mystr. Thus, sizeof(mystr) will always return the size of a pointer for the system you are on.
Therefore, the sizeof() operator cannot be used to determine things like capacity of arrays unless the array is locally declared. It needs to be used with caution. There are AI bots and writing that will suggest that you use sizeof() to determine capacity of arrays but it can fail spectacularly if used in the wrong context. Be sure to consider all this when you use this operator.