Explain this program.

  • #1
#include<stdio.h>
void main()
{
char c[]="gate2011";
char *p=c;
printf("%s",p+p[3]-p[1]);
}
 

Answers and Replies

  • #2
CompuChip
Science Advisor
Homework Helper
4,306
47
Doesn't look like rocket science. What do you think will happen? What actually happens when you run it?
 
  • #3
722
24
It apparently takes the adress of the string + 65-61= adr + 4. Now I don't know but this seems not aligned, but it means maybe adr + 4 bytes, hence it maybe prints '2011', but I have not checked this for real.
 
Last edited:
  • #4
CompuChip
Science Advisor
Homework Helper
4,306
47
The trick is the way that pointers and arrays are equivalent in C++.
If you have an array
Code:
int[] a;
then a is a pointer to an int, and &a[4] and *(a + 4) both point to address of the 5th array element.
So the pointer p points at the beginning of the string, p[4] - p[1] is the length of the memory block used by the first four characters and the sum is a pointer to the place in memory where the '2' is stored. Since strings are terminated by a null (\0) the statement is equivalent to
Code:
    char p[] = { '2', '0', '1', '1', '\0' };
    printf("%s", p);

You could actually reach the same thing through
Code:
#include<stdio.h>
void main()
{
    char c[]="gate2011";
    // No need to introduce a new name, c is already a char*
    // char* p = c; 
    printf("%s", (c + 4));
}
 
  • Like
Likes 1 person

Related Threads on Explain this program.

  • Last Post
Replies
6
Views
2K
  • Last Post
Replies
5
Views
1K
  • Last Post
Replies
4
Views
2K
Replies
5
Views
208
  • Last Post
4
Replies
89
Views
2K
  • Last Post
Replies
10
Views
2K
Replies
6
Views
3K
V
Replies
2
Views
1K
Replies
3
Views
9K
  • Last Post
Replies
4
Views
2K
Top