when I got an array of pointers and a pointer why sizeof the array of poninters is equal to the sizeof pointer? for example:
char matrixp;
char **m;
printf("%llu", sizeof matrixp);
printf("%llu", sizeof m);
gives back the same output. is there a way I can get the total size in bytes for example of
char *vet[10]
? (that should be 80).
CodePudding user response:
To answer the question in the title - pointers to different types (including pointer types) do not all have to be the same size. The only requirements are:
char *andvoid *have the same size and alignment;- Pointers to qualified types have the same size and alignment as pointers to their unqualified equivalents (e.g.,
sizeof (int *) == sizeof (const int *); - All
structpointer types have the same size and alignment; - All
unionpointer types have the same size and alignment;
So it's not guaranteed that an int * is the same size as an int ** or
an int (*)[N], but for commodity hardware like x86_64 it tends to be true.
Now, for your specific questions:
First of all, a sizeof expression has type size_t, for which we need to use the %zu conversion specifier in printf. Using %llu on a size_t argument is technically undefined behavior. Rewrite those statements as
printf("%zu", sizeof matrixp);
printf("%zu", sizeof m);
and see if you still get the same output. You shouldn't because you've defined matrixp as a plain char (at least in the code you've posted here), and sizeof (char) is 1 by definition, and I will guarantee no pointer type is only one byte wide (unless you're working on a system that only has 256 addressable memory locations).
Secondly, sizeof evaluates to the number of bytes in the operand (whether the operand is a type name or expression). sizeof vet will yield the total number of bytes used by the vet array (10 * sizeof (char *)). To get the number of elements (10), you'll have to divide the result of sizeof vet by the size of an individual element, sizeof vet[0] (or sizeof *vet, which evaluates to the same thing).
CodePudding user response:
All pointer have the same size (8 bytes). If you want to get the total size of an array (like char *vet[10]), you have to declare it as an array (with []) and not as a pointer (char **vert). *vert[10] is an array of 10 pointers while **vert is a pointer to the start of an area of memory containing pointers.
For example
#include <stdio.h>
int main(void){
char *chars[] = {"hello", "world", "pointers"}; // declared as an array of strings/pointers
printf("%zu\n", sizeof(chars[0])); // pointer to the start of 'hello' (size is 8)
printf("%zu\n", sizeof(chars[1])); //pointer to start of 'world' (still 8 bytes)
printf("%zu\n", sizeof(chars)); // refers to the whole array (24 bytes)
char **m; // a pointer pointing to the first pointer in m (not an array)
char *n; // another pointer pointing to the first letter in n
n = "pointer";
printf("%zu\n", sizeof(n)); // 8
printf("%zu\n", sizeof(m)); // 8
return 0;
}
