in Programming in C edited by
745 views
2 votes
2 votes
main(){

    int S[6] = {126,256,512,1024,2048,4096};

    int *x=(int *) (&S+1);

    printf (“%d”,x);

}

int is 4 bytes; array starts from 2000 .

The answer is 2024 I am getting 2004.

Please explain the concept. If possible provide a resource.

in Programming in C edited by
745 views

4 Comments

edited by
i'm not getting the solutions?
0
0
edited by

Your array S is of size 6, so &S gives a pointer to S i.e a data structure of size 24bytes. If you do &S + 1, you are doing 2000 + 24*1. You can use S[i] or simple *(S+i) to access integers in the array.
TLDR: &S gives a pointer to a data structure of size 24bytes. S gives a pointer to an integer.

Try running this:
 

#include <stdio.h>

int main(){
	int arr[4] = {1,2,3,4};
	int *ptr = (int*)(&arr + 1);
	printf("%u\t %u\n",&arr, ptr);
	printf("%u\n",arr+1);
	return 0;
}

 

3
3
pointing to first garbage value after 4096 (&s+1) means point to element just after array s so we have first element which is stored at 2000 and after crossing 6 location each of 4 bytes i.e total of 24 bytes we get to that location
0
0
Thanks i got it!
0
0

2 Answers

4 votes
4 votes
int *x=(int *) (&S+1);

size of S is $4 \times 6 = 24$ bytes 

(&S + 1) == (2000 + 1 * 24) == 2024

1 vote
1 vote
When you do &S + 1 than it will work as follows

&S + 1*sizeof(S)

= 2000 + 24

=2024

This address will be referred by x and on print we get 2024

Related questions