2

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
Wasiim Ouro-sama
  • 1,485
  • 2
  • 12
  • 15

3 Answers3

7

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.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • so char*[] contains char* elements which store the address of their corresponding characters? – Wasiim Ouro-sama May 29 '16 at 21:14
  • @funTertain `char *[]` is an array of `char` pointers. You need to supply character pointers or string literals to initialize this array. For example, you could do this: `char *text[] = {"quick", "brown", "fox"}`. Now you have three pointers with three addresses of null-terminated C strings. When you supply `char` literals instead of initialization, your pointers store the values of these literals, which illegal but useless. – Sergey Kalinichenko May 29 '16 at 21:19
  • what's the point of having a char* array if they only store characters and why is this even possible to begin with? – Wasiim Ouro-sama May 29 '16 at 21:19
  • 1
    @funTertain: The thing is, C doesn't have a string datatype—instead one usually stores strings in a contiguous block of memory, terminated by the null character, and keeps a pointer to the first character in the string as a `char *`. So, if one wants to have of an array of such pointers (i.e. each element points to a null-terminated string, as demonstrated in @dasblinkenlight's comment above), the datatype would be `char *[]`. – eggyal May 30 '16 at 08:28
1

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.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
1

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.

Community
  • 1
  • 1
user3078414
  • 1,942
  • 2
  • 16
  • 24