That looks reasonable. "sizeof expression" produces the same result as
"sizeof(type)", where "type" is the type of "expression". Since types
can always be determined by the compiler at compile time (unless they
involve variable length arrays (VLAs), but that's a more advanced
topic), a sizeof expression is normally replaced by the appropriate
constant at compile time.
In this case, pointerStr[i] has a type of char*, regardless of the value
of i. On you machine, sizeof(char*) is 4, which is pretty common.
pret.info[i].name has a type of char[40], regardless of the value of i,
and sizeof(char[40]) is guaranteed to be exactly 40, so that's why you
got the results that you did.
> If I want to know the size of each and every string in PointerStr then
> how to find it? Is it possible only using strlen ?
That's precisely what strlen() is for. There are other ways of getting
the same number, but there's no reason for using any of the other ways
if strlen() is already provided by the library (as it will be for any
hosted implementation of C).
> ... do we have some
> other way ? How this variable length array is stored in memory ?
Nothing you've written here is a VLA. I'll discuss VLA's below. For now,
I'll explain what's going on in your actual code.
Each of the string literals in your code, such as "123456, ", causes
an unnamed array to be statically allocated, big enough to store every
character in the string plus a terminating null character '\0'. The
string literal itself has a value which is a pointer to that the first
character of that array. In other words,
char * p = "123456, ";
Is functionally equivalent to
char unnamed_array[] = {'1', '2', '3', '4', '5', '6', ',',
' ', ' ', ' ', ' ', ' ', '\0'};
char *p = &unnamed_array;
As explained above, "sizeof p" is exactly equivalent to
"sizeof(char*)", giving a value of 4 on your system, which is apparently
not what you want. strlen(p), on the other hand, will use the pointer
value of p, which points at the first character of the unnamed array
storing the contents of the string literal. It will search forward,
starting at that point, until it finds the terminating null character.
It counts how often it has to increment the pointer during the search,
in this case, 12 times. That's the value it will return. Hopefully, that
is the number you want?
A VLA is something quite different. VLAs are a feature that was
introduced in C99. Here's an example:
void func(int length)
{
char vla[length];
...
When func is called, an array of char of the specified length is
allocated to store vla. Unlike normal sizeof expressions, "sizeof vla"
cannot be evaluated at compile time. It has the same value as
"sizeof(char[length])", which is simply "length", a value which cannot
be determined until the function has actually been called.
--
James Kuyper