Wasiim Ouro-sama
Wasiim Ouro-sama

Reputation: 1565

char*[] elements take 4 bytes each and char[] take 1 byte each?

why is the output of the below code the case?

char str[] = {'i', 't', 'i', 's', 'm', 'e', '\0'}; //this code equates to 7 bytes
char* str[] = {'i', 't', 'i', 's', 'm', 'e', '\0'}; //this code equates to 28 bytes

Upvotes: 2

Views: 1277

Answers (3)

user3078414
user3078414

Reputation: 1937

Size of a pointer defaults to the environment address width, because pointers must be made capable of covering theoretically available address space, i.e. pointing at any of the addresses possible within current system architecture. In a 32-bit system it is 32-bit (2^32 possible addresses), in a 64-bit system 64-bit (2^64 possible addresses), no matter if it points at a char or a double. Size of an array of pointers equals number_of_array_elements*size_of_pointer.

#include <stdio.h>

int main (void)
{
  char  str[]  = {'i', 't', 'i', 's', 'm', 'e', '\0'}; //this code equals 7*sizeof(char)
  char* str1[] = {"i", "t", "i", "s", "m", "e", "\0"}; //this code equals 7*sizeof(char*)

  printf("%zu\t%zu\n", sizeof(str), sizeof(str1));
  return 0;
}

This SO post may also be worth reading.

Upvotes: 1

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53016

Your compiler should be throwing a warning for this

char *str[] = {'i', 't', 'i', 's', 'm', 'e', '\0'};

the type of the actual elements is incompatible with the type of the array elements.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726899

This code does not do what you think. It uses char constants to initialize elements of a char* array of pointers. Such "pointers" do not point to your characters; instead, they have numeric values of their corresponding characters!

Each character pointer on your system is 4-bytes long, which explains the result.

Upvotes: 7

Related Questions