Reflection
Reflection

Reputation: 2106

Datatype declaration significance in pointer to pointer (C/C++)

Is there a difference between pointer to integer-pointer (int**) and pointer to character-pointer (char**), and any other case of pointer to pointer?

Isn't the memory block size for any pointer is the same, so the sub-datatype doesn't play a role in here?

Is it just a semantic distinction with no other significance?

Why not to use just void**?

Upvotes: 3

Views: 155

Answers (3)

Eric Postpischil
Eric Postpischil

Reputation: 222352

Most C implementations use the same size and format for all pointers, but this is not required by the C standard.

Some machines do not have byte addressing, so the C implementation implements it by using shifts and other operations. In these implementations, pointers to larger types, such as int, may be normal addresses, but pointers to char would have to have both a machine address and a byte-within-word offset.

Additionally, C makes use of the type information for a variety of purposes, including reducing mistakes made by programmers (possibly giving warnings or errors when you attempt to use a pointer to int where a pointer to float is needed) and optimization. Regarding optimization, consider this example:

void foo(float *array, int *limit)
{
     for (int i = 0; i < *limit; ++i)
         array[i] = <some calculation>;
}

The C standard says a compiler may use the fact that array and limit are pointers to different types to conclude that they do not overlap. Given this rule, the C implementation may evaluate *limit once when the loop starts, because it knows it will not change during the loop. Without this rule, the compiler would have to assume that one of the assignments to array[i] might change *limit, and it would have to load *limit from memory in each iteration.

Upvotes: 5

Daniel Daranas
Daniel Daranas

Reputation: 22624

Why should we use void** when you want a pointer to a char *? Why should we not use char **?

With char **, you have type safety. If the pointer is correctly initialized and not null, you know that by dereferencing it once you get a valid char * - and by dereferencing that pointer, in turn, you get a char.

Why should you ignore this advantage in type safety, and instead play pointer Russian roulette with void**?

Upvotes: 5

ScarletAmaranth
ScarletAmaranth

Reputation: 5101

The difference is in type-safety. T** implicitly interprets the data as T. void**, however, needs to be manually casted first. And no, pointers are not all 4 / 8 bytes on 32 / 64bit architectures respectively. Member function pointers, for instance, contain offset information too, which needs to be stored in the pointer itself (in the most common implementation).

Upvotes: 5

Related Questions