schanti schul
schanti schul

Reputation: 711

Character Arrays versus Character Pointers regarding size

Quote from an article I read:

*...Consider the following two variables:

char s6[ ] = "hello", *s7 = "hello";

s6 allocates space for exactly 6 bytes; s7 allocates space for 10 ( typically ) - 6 for the characters plus another 4 for the pointer variable.*

Curious about to who holds the address of s6 (of the first char in the array)? And how does s6 'save' the 4 bytes for the pointer?

Upvotes: 0

Views: 105

Answers (3)

42LeapsOfFaith
42LeapsOfFaith

Reputation: 144

Curious about to who holds the address of s6 (of the first char in the array)? And how does s6 'save' the 4 bytes for the pointer?

The compiler/ linker hold this address. It is treated as a constant, because it can't be modified at run time. I hope this helps.

Upvotes: 2

Draconis
Draconis

Reputation: 3461

To put it simply, it's not stored anywhere in your program. Only the compiler keeps track of it.

Under the hood:

  • s6 means "address XXXXXXXX: a block of six bytes, holding the values 'H', 'e', 'l', 'l', 'o', 0"
  • s7 means "address YYYYYYYY: a block of four bytes, holding the values ZZ, ZZ, ZZ, ZZ"
  • *s7 means "address ZZZZZZZZ: a block of one byte, holding the value 'H'"

The program doesn't actually have to store the value XXXXXXXX anywhere; the compiler just inserts the value XXXXXXXX anywhere that you use s6.

Similarly, the program doesn't have to store YYYYYYYY anywhere, but it does store ZZZZZZZZ, because you specifically said so (you said to assign the value ZZZZZZZZ to the variable s7).

If you want to store XXXXXXXX somewhere, though, you can easily do so:

char my_pointer* = &s6;

Now my_pointer means "address WWWWWWWW: a block of four bytes, holding the values XX, XX, XX, XX".

P.S. This is assuming you're on a system with four-byte pointers; nowadays, it's more likely that a pointer is eight bytes, or 64 bits.

Upvotes: 4

Sourav Ghosh
Sourav Ghosh

Reputation: 134316

s6 allocates space for exactly 6 bytes; s7 allocates space for 10 ( typically ) - 6 for the characters plus another 4 for the pointer variable.

No, that's not correct.

s6 has space for exactly 6 bytes, s7 has space (size) of that of a pointer (4 or 8 bytes usually, depending on your architecture) and it points to the string used to initialize it.

In other words,

  • size of s6 is sizeof ("hello").
  • size of s7 is sizeof (s7), i.e, sizeof (char *)

You can execute the below program to check the sizes:

#include  <stdio.h>

int main(void)
{
    char s6[ ] = "hello", *s7 = "hello";

    printf("s6 = %zu\n", sizeof (s6));
    printf("s7 = %zu\n", sizeof (s7));

    return 0;
}

On my system, they yield:

s6 = 6 // sizeof ("hello"), or , sizeof (char [6])

s7 = 8 // sizeof (char *)

Upvotes: 3

Related Questions