689 views

1 Answer

4 votes
4 votes

First read  https://www.geeksforgeeks.org/sizeof-operator-c/

sizeof() operator returns size_t type, https://www.geeksforgeeks.org/size_t-data-type-c-language/

 

#include <stdio.h> 
int main() 
{ 
	int a = 1; 
	char d[] = "ab"; 
	printf("%ld", sizeof(d)); 
	return 0; 
} 

in general,  size of array = no.of elements* size of each element.

Note that, there is a null character present at end of the string by default. 

Output :- d is character array ==> no.of elements =  3 including null character, and each element takes 1 Bytes ==> 3 Bytes as output.

 

#include <stdio.h> 
int main() 
{ 
	int a = 1; 
	char d[] = "ab"; 
	printf("%ld", sizeof(a+d)); 
	return 0; 
} 

in this case integer is added to the character array ==> pointer + int ==> result type is pointer

Output :- size of pointer.

 

Now you may have doubt that, why sizeof(d) doesn't returns size of pointer ?

it is due to " type assigned to d during declaration. ", but in case of sizeof(d+a), type once again calculated, So it returns size of pointer ( Thanks to @arjun sir, for clarification. )


IMPORTANT POINT :-  sizeof never evaluates the expression value, it just evaluates the type of expression only.

https://www.geeksforgeeks.org/anything-written-sizeof-never-executed-c/

https://www.geeksforgeeks.org/why-does-sizeofx-not-increment-x-in-c/

Related questions

1 votes
1 votes
1 answer
1
radha gogia asked Jul 10, 2018
1,738 views
If I have an array :int a [3][4] ; How to evaluate below Outputs ? 1. sizeof(*a) 2.sizeof( a) 3. sizeof(a) Please explain precisely .
1 votes
1 votes
2 answers
2
raushan sah asked May 24, 2018
1,173 views
#include<stdio.h int main() { char *s="\123456789\n"; printf("%d", sizeof(s)); return 0; }why this piece of code gives output $8$please explain. thanx
1 votes
1 votes
1 answer
3
saumya mishra asked May 15, 2018
1,666 views
#include<stdio.h int main(void) { printf("bytes occupied by '7' = %d\n", sizeof('7')); printf("bytes occupied by 7 = %d\n", sizeof(7)); printf("bytes occupied by 7.0 = %d...
3 votes
3 votes
1 answer
4
Lakshman Bhaiya asked Apr 23, 2018
966 views
Q)What is the output of the following C program fragment?Assume size of an integer is 4 Bytes#include<stdio.h>int main(){int i = 5;int var = sizeof( i++);printf("%d %d",i...