-1
#include<iostream>
using namespace std;
int main(){
    double a;
    double b[10];
    char *c;
    char r[12]="appleeeeeee";
    c=r;

cout<<sizeof c<<endl;     //Why is this 8 and not equal  to 12 i.e sizeof(r)    
cout<<sizeof r; 
}

q1. Isn't the array name a pointer to the beginning of the array?? If so then why does the sizeof operator evaluates to two different values in the above code.

i.e Why sizeof c yields 8 while sizeof r yields 12 even though both of them are pointer to a character.

Why is the size of the array r[12] printed in the second case?

this question may look like the duplicate of this but it doesnt answer my question.

rimalroshan
  • 868
  • 2
  • 12
  • 28

2 Answers2

1

In many cases, an array decays to a pointer to the first element. This is not the case however for the sizeof operator. It can distinguish between an array and a pointer and give the correct value. Since c is a pointer to a char the value you're getting is the size of a pointer. The fact that c contains the address of the first element of r doesn't matter.

Also, value of the sizeof operator is computed at compile time, so whatever value a variable might have is not relevant to sizeof. The only exception is for variable length arrays in C.

dbush
  • 186,650
  • 20
  • 189
  • 240
  • "value of the sizeof operator is computed at compile time, so whatever value a variable might have is not relevant to sizeof" this perfectly explains why sizeof(c) would print 1 regardless of the value its pointing to but Can you explain further on why sizeof(r) evaluates to 12. thanks! – rimalroshan Nov 09 '17 at 03:37
1

sizeof c is reporting the size of the pointer, not what it points to (you're on a system with 64 bit pointers, thus a size of 8 to hold a pointer). Even sizeof *c wouldn't help, because the pointer is to the first element of r, not the "array", so sizeof *c would just report the same thing as sizeof r[0], that is 1.

ShadowRanger
  • 124,179
  • 11
  • 158
  • 228