-3
#include<stdio.h>

int main() {
char *arr[] = { "sunbeam ","dac","wimc","pune","karad" };
char **ptr;
int i;
printf("size : %d\n",sizeof(arr));

}

this c program showing 40 as output please explain me how it comes.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621

2 Answers2

4

Two things: arr is an array of pointers, and sizeof returns the size in bytes.

Since arr is an array of five pointers to char, the result of sizeof(arr) is equal to 5 * sizeof(char *). Which on a typical 64-bit system (where pointers are 64 bits, i.e. 8 bytes) is 40 bytes.

Furthermore, you use the wrong format to print the result of sizeof. You should be using "%zu" (the z modifier because the argument is a size_t, the u type because it's unsigned). See e.g. this printf (and family) reference for more information.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • #include int main() { char *arr[] = { "sunbeam ","dac","wimc","pune","karad" }; char **ptr =arr+2; printf("%s",++ptr[arr-ptr]-1); return 0; } sir please can you explain me how this program will execute step by step – Mahendra Shoor Nov 26 '17 at 05:32
  • 3
    @MahendraShoor If you have another question, the *ask* another question. Please take some time to read [the help pages](http://stackoverflow.com/help), especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). Also please [take the tour](http://stackoverflow.com/tour) and [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask). – Some programmer dude Nov 26 '17 at 05:35
0

Pointers will be size 2 on a 16-bit system, 4 on a 32-bit system, and 8 on a 64-bit system.
Your code(Simplified for explanation) :

#include <stdio.h>   
int main() {
char*arr[] = { "a","b","c","d","e" };
char *arr1;
char **arr2;
 printf("Size of Array : %zu \n", sizeof(arr) );
 printf("Size of Array1 : %zu \n",sizeof(arr));
 printf("Size of Array2 : %zu \n",sizeof(arr));
 return 0;
 }

Output:

 main
 Size of Array : 40
 Size of Array1 : 8
 Size of Array2 : 8

Your program has nothing to do with the values inside array
char *arr[] = { "a","the largest string in the array will still take 8 bytes","c","d","e" }; the pointer to array is a pointer to all those values, takes 8 bytes for each index in 64 architecture. sizeof(arr) thus returns 40bytes for 5 elements .

Zahid Khan
  • 2,130
  • 2
  • 18
  • 31