GATE / CS ARCHIVE

SUBJECT COLLECTION

Programming in C · Pointers & Memory

28 questions, newest first

GATE CSE has asked 28 questions on Pointers & Memory (Programming in C) from 2000 to 2026, in 22 of the 46 papers; the most recent is in GATE CSE 2026 Set 2. In the last five years it carried 1 marks per 100-mark paper on average, against 1.1 since 2003. Since 2014 the questions have been 11 MCQ and 9 NAT. 4 groups of questions here are solved the same way; “One per method” keeps the newest of each.

Browse topics
2 marks · NAT
Report issue

Tracing pointer reassignment in C

Pointers & Memory

Question 60, GATE 2026: Find the printed c for this statement sequence in main: int *ptr,a,b,c; a=5; b=11; c=20; ptr=&a; *ptr=c; ptr=&c; a=*(&b); c=*ptr-a; printf("%d",c);. Assume successful compilation and execution.
Tap to enlarge
Answer & solution

Official answer: 9

Step through it (14 steps)

Givens and goal

Find the printed c for this statement sequence in main: int *ptr,a,b,c; a=5; b=11; c=20; ptr=&a; *ptr=c; ptr=&c; a=*(&b); c=*ptr-a; printf("%d",c);. Assume successful compilation and execution.

Approach

Track both the pointer target and the object values after every assignment.

Step-by-step solution

1. Initially a=5,b=11,c=20. The assignment ptr=&a stores a’s address in ptr; it does not change any integer value.
2. Then *ptr=c writes the current value of c into the object pointed to by ptr, which is a. The state becomes a=20,b=11,c=20, with ptr still pointing to a.
3. Next ptr=&c redirects the pointer to c without copying any old pointed-to value. The expression *(&b) is simply b, so a=*(&b) sets a=11. Now a=11,b=11,c=20 and ptr points to c.
4. In c=*ptr-a, the right-hand side reads the old value c=20 through ptr and subtracts a=11. The assignment therefore stores c=9, and printf prints 9.
5. This assignment is well-defined: the old c is read to calculate its new value. The crucial distinction is between changing ptr itself and assigning through *ptr to the current target.

Original paper, page 40 · Answer key

1 mark · NAT
Report issue

Following a pointer argument back to its object

Pointers & Memory

Question 34, GATE 2025: C function foo(int *p,int x) executes *p=x. In main, a=20,b=25, pointer z is assigned &a, then foo(z,b) is called and a is printed. What integer is printed?
Tap to enlarge
Answer & solution

Official answer: 25

Approach: Distinguish copying an argument from modifying the object that a copied pointer designates.
Initially a contains 20 and b contains 25. The assignment z=&a makes z hold the address of a. On calling foo(z,b), the parameter p receives a copy of that same address, while x receives the value 25.
Inside foo, the expression *p is the integer object at p’s address, which is main’s a. Therefore *p=x stores 25 into a. Returning from foo discards its local parameter objects but does not undo the write to a.
The subsequent printf of a prints 25. C still passes arguments by value: p itself is copied, but the copied address can be dereferenced to change an object owned by the caller. If the function had assigned only p or x, that would be a different operation; the dereferencing assignment is decisive.

Original paper, page 34 · Answer key

2 marks · NAT
Report issue

Pointers & Memory

Question 62, GATE 2025: Find the integer output of this C fragment:
int a; int arr[5]={30,50,10}; int *ptr;
ptr=&arr[0]+1;
a=*ptr;
(*ptr)++;
ptr++;
printf("%d",a+(*ptr)+arr[1]);
Tap to enlarge
Answer & solution

Official answer: 111

Step through it (12 steps)

Array initialization yields arr=[30,50,10,0,0]; omitted entries are zero-initialized. Pointer arithmetic &arr[0]+1 advances by one int element, so ptr initially points to arr[1], whose value is 50. The assignment a=*ptr copies 50 into a.

The parentheses in (*ptr)++ make the increment apply to the pointed-to value. Hence arr[1] becomes 51 while ptr stays at arr[1]. The copied variable a remains 50. The next statement ptr++ instead increments the pointer itself, moving it to arr[2], whose value is 10.

At the print, the three terms are a=50, *ptr=10, and arr[1]=51. Their sum is 50+10+51=111. The operations occur in separate statements, so their sequencing is unambiguous. Confusing (*ptr)++ with *ptr++ would mix up value mutation and pointer advancement and give the wrong trace. Answer: 111.

Original paper, page 46 · Answer key

2 marks · MCQ
Report issue

Pointer distance versus pointed-to value difference

Pointers & Memory

Question 36, GATE 2024: C code declares double a[2]={20.0,25.0}; sets p=a and q=p+1; and prints "%d,%d" with (int)(q−p), (int)(*q−*p). Which output? A 4,8; B 1,5; C 8,5; D 1,8.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Approach: Evaluate the pointer expression and the dereferenced arithmetic expression separately.

1. Derivation. p points to a[0] and q=p+1 points to a[1]. Pointer subtraction counts array elements, not bytes, so q−p=1. The values differ by 25.0−20.0=5.0, cast to 5. The output is 1, 5, option B, independent of sizeof(double).

2. Explanation and checks. Adding one to a double pointer moves by the storage occupied by one double, but subtracting two double pointers converts the byte displacement back into an element count. Thus it is one regardless of the implementation’s double size. Dereferencing yields the numeric values 25.0 and 20.0, whose difference is exactly 5.0 here. The integer casts produce 1 and 5 for the two %d arguments; they do not turn the pointer difference into a byte distance.

The printed program uses typographic quotation marks and en dashes. Interpreting these as the intended ASCII C quotation marks and subtraction operators gives the stated answer B; copied literally, the printed characters do not form valid C tokens.

Original paper, page 24 · Answer key

1 mark · MCQ
Report issue

Pointers & Memory

Question 21, GATE 2022: Find the output of this ANSI C main body: int x=1,z[2]={10,11}; int *p=NULL; p=&x; *p=10; p=&z[1]; *(&z[0]+1)+=3; printf("%d, %d, %d\n",x,z[0],z[1]); return 0; (stdio.h included). A 1,10,11; B 1,10,14; C 10,14,11; D 10,10,14.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Initially x=1 and z={10, 11}. Assigning 10 through p=&x changes x to 10. After p points to z[1], the expression *(&z[0]+1) denotes that same second element; adding 3 changes it to 14. z[0] stays 10. The printed values are 10, 10, 14, D.

Pointer reassignment changes what p refers to; it does not copy values between x and z. After *p=10, x remains 10 even after p moves. Array pointer arithmetic advances by one int, so &z[0]+1 is &z[1], not a byte address or z[0].

Original paper, page 17 · Answer key

1 mark · MCQ
Report issue

Pointers & Memory

Question 10, GATE 2021: ANSI C declares int arr[4][5] and initializes arr[i][j]=10*i+j for 0≤i<4,0≤j<5. It prints *(arr[1]+9) with %d. Offered outputs: A 14; B 20; C 24; D 30. Explain the intended result and the language-standard issue.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Our answer: C under intended flattening; undefined in strict C

The intended contiguous-address calculation begins at row1, column 0, linear index 5; advancing 9 integers reaches index 14=row2, column 4, whose initialized value is 24, C. However arr[1] decays to a pointer into the five-element row subarray. Adding9 goes beyond that array and its one-past position, so the expression has undefined behavior under C pointer-arithmetic rules. Contiguous storage of the outer array does not legalize this cross-row pointer arithmetic. The official C is retained as the intended exam answer, not a portable guarantee.

The intended memory layout has rows 0–4,10–14,20–24,30–34. The desired element is arr[2][4], which is a portable way to express it. Do not run this original expression and treat one observed compiler output as a proof of defined behavior. The official option describes the conventional exam address calculation only.

Original paper, page 60 · Answer key

2 marks · MCQ
Report issue

Pointers & Memory

Question 35, GATE 2021: C Node has int value; Node *next. Allocate head=boxE, set value=0. For index=1..3 allocate boxN, set boxE->next=boxN, boxN->value=index, boxE=boxN. Then for index=0..3 print head->value, assign head=head->next, and print head->value again. No final next initialization occurs. A five nodes created; B infinite loop; C missing return causes compile error; D uninitialized pointer dereferenced, possibly runtime error.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

The initial allocation plus three loop allocations create four nodes with values 0, 1, 2, 3. The final node’s next field is never initialized. The second loop advances head and dereferences it again each iteration; on the fourth iteration it reads that uninitialized next pointer and uses it for head->value. This is undefined behavior and may cause a runtime error, D. The loops themselves have bounded iteration counts.

Before the second loop, the chain is 0→1→2→3→uninitialized. The first three iterations safely advance to nodes 1,2,3 if allocation succeeds. The last iteration prints 3, then follows the indeterminate pointer and dereferences it. Initializing next to NULL alone would still leave the unconditional extra dereference invalid; correct traversal tests the pointer before using it. Allocation failure is another issue, not needed for the intended diagnosis.

Original paper, page 75 · Answer key

1 mark · NAT
Report issue

Pointers & Memory

Question 22, GATE 2020: Find the output of this C program:
#include <stdio.h>
int main(void) {
 int a[4][5]={{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15},{16,17,18,19,20}};
 printf("%d\n", *(*(a+**a+2)+3));
 return 0;
}
Tap to enlarge
Answer & solution

Official answer: 19

Step through it (6 steps)

Worked explanation

Track pointer types: in this expression a decays to a pointer to an array of five ints, so adding 1 advances by a whole row. *a denotes row zero, and a is its first integer, 1. Therefore a+a+2 is a+3. Dereferencing gives row three, which in the addition +3 decays to a pointer to its first int. Adding 3 selects its fourth entry and the outer dereference reads 19. Written with subscripts the expression is a[3][3], not a[0][6] or a linear six-element offset. Both row and column indices are valid.

Derivation and answer

Here a=a[0][0]=1. Thus a+a+2=a+3 points to the fourth row. Dereferencing that row and adding 3 selects a[3][3]=19. All pointer arithmetic stays within the relevant row/outer array, so the printed expression has the defined result 19.

Original paper, page 8 · Answer key

1 mark · NAT
Report issue

Array indexing relative to an interior pointer

Pointers & Memory

Question 24, GATE 2019: A C program initializes int arr[]={1,2,3,4,5,6,7,8,9,0,1,2,5}; and int *ip=arr+4; then prints ip[1] using the %d conversion. Find the integer displayed.
Tap to enlarge
Answer & solution

Official answer: 6

Method: identify the pointer's base element, then apply C's definition of the subscript operator.

1. C array indices start at zero. Thus arr[0]=1, arr[1]=2, arr[2]=3, arr[3]=4, arr[4]=5, and arr[5]=6. “Index 4” denotes the fifth element, not the fourth.
2. In the expression arr+4, arr converts to a pointer to its first element, &arr[0]. Adding 4 to an int pointer advances it by four int elements, not by four bytes. Therefore ip=&arr[4], pointing at the value 5.
3. For a pointer p, C defines p[k] as *(p+k). Consequently ip[1]=*(ip+1): advance one more int from arr[4], then read the value at that location.
4. Substitute the pointer value explicitly: *(ip+1)=*((arr+4)+1)=*(arr+5)=arr[5]=6.
5. The access stays within the 13-element array and does not modify either ip or arr. The %d conversion prints the selected integer, followed by the newline specified in the program.

Result: 6. ip[0] would be 5, whereas ip[1] is 6; ip[1] is not the same as arr[1] because the two indexing expressions use different base pointers. No assumption about the byte size of int is needed.

Original paper, page 8 · Answer key

2 marks · NAT
Report issue

Value subtraction versus pointer subtraction

Pointers & Memory

Question 53, GATE 2019: In C, a={2,4,6,8,10}, sum=0, and int *b=a+4. For i=0 through 4, execute sum=sum+(*b-i)-*(b-i); then print sum as an integer. What is printed?
Tap to enlarge
Answer & solution

Official answer: 10

Step through it (24 steps)

1. Pointer b is initialized to the final array element a[4]. No statement changes b, so *b remains 10 throughout the loop.
2. Distinguish the two expressions carefully. (*b-i) subtracts i from the value 10. By contrast, *(b-i) first moves the pointer i array positions backward and then reads a[4-i]. Pointer arithmetic counts int elements, not bytes.
3. For i=0,1,2,3,4, the first expression takes values 10,9,8,7,6. The second reads 10,8,6,4,2. Their differences are therefore 0,1,2,3,4.
4. Starting from zero, sum accumulates 0+1+2+3+4=10. Equivalently, a[4-i]=10−2i, so each summand is (10−i)−(10−2i)=i.
5. The output is 10 followed by a newline. All dereferences stay within a[0] through a[4]. The minus sign is subtraction, not a decrement of b, and confusing these operations would produce a different trace.

Original paper, page 16 · Answer key

1 mark · MCQ
Report issue

Reading char members through a pointer

Pointers & Memory

Question 2, GATE 2018: C declares struct Ournode { char x,y,z; }; initializes p={'1','0','a'+2}; sets q=&p; and prints printf("%c, %c", *((char*)q+1), *((char*)q+2)). Choices: A 0, c; B 0, a+2; C '0', 'a+2'; D '0', 'c'.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Our answer: A under conventional layout and character encoding

Method

The cast occurs before pointer arithmetic: a char pointer advances by one byte, whereas adding 1 to a struct pointer would advance by a whole struct. Under the intended layout, offsets 1 and 2 select y and z. The expression 'a'+2 is evaluated numerically during initialization, not printed as source text. The %c conversion prints the represented character without surrounding quote marks. Keep the implementation assumptions below separate from the intended exam output.

Solution

With consecutive char members at byte offsets 0, 1, 2, the two dereferences read y and z. In an ASCII-compatible execution character set, y is the character 0 and z is c from a+2, giving 0, c, A. Strict ISO C permits internal struct padding and does not universally require contiguous alphabetic codes. The result therefore assumes the conventional padding-free char layout and character encoding used by the question.

Original paper, page 4 · Answer key

2 marks · MCQ
Report issue

Pointer swapping by value and address

Pointers & Memory

Question 29, GATE 2018: In C, str1="Hi", str2="Bye". fun1(char *s1,char *s2) swaps its local pointer variables using a temporary. fun2(char **s1,char **s2) swaps *s1 and *s2. main calls fun1(str1,str2), prints both strings, calls fun2(&str1,&str2), then prints both. Choices A Hi Bye Bye Hi; B Hi Bye Hi Bye; C Bye Hi Hi Bye; D Bye Hi Bye Hi.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Method

C passes arguments by value in both calls. In fun1 the copied values happen to be addresses of characters, so replacing those local copies cannot replace main’s variables. In fun2 the copied values are addresses of main’s pointer variables; dereferencing them selects those actual variables, which the assignments can modify. Neither routine edits the string literals. This distinction is between swapping pointed-to pointers and swapping local pointer copies, not between two language-level parameter-passing modes.

Solution

fun1 swaps only local copies of the pointer values, leaving main’s strings unchanged: Hi Bye. fun2 receives their addresses and swaps the actual pointer variables, so the second output is Bye Hi. The whole output is Hi Bye Bye Hi, A.

Original paper, page 12 · Answer key

1 mark · MCQ
Report issue

Pointers & Memory

Question 8, GATE 2017: The printed C fragment is:
typedef struct node { int data; node* next; } node;
void join(node* m,node* n) { node* p=n; while(p->next != NULL) { p=p->next; } p->next=m; }
Assume m and n point to valid NULL-terminated linked lists. A always appends m to n; B either null-pointer dereference or appends m to n; C always null-pointer dereference; D always appends n to m. The source typedef is retained literally, not silently repaired.
Tap to enlarge
Your answer
Answer & solution

Official answer: B

Our answer: B under intended corrected C declaration

1. Trace the pointer, not the data fields: p starts at n, and each iteration follows the next link. For a nonempty terminating n list, the loop stops at its final node.

2. The assignment p->next=m connects that final node to the head of m. It therefore appends m to n, including the case m is empty.

3. An empty list can be represented by n=NULL; then even the first test p->next dereferences NULL. This prevents the “for all inputs” claim A. Intended B assumes a valid declaration and disjoint lists for an acyclic concatenation.

node* appears inside the typedef before node is declared as a typedef name. Standalone C needs struct node* next or an earlier forward typedef. This source defect is not repaired in the displayed code.

Original paper, page 5 · Answer key

1 mark · MCQ
Report issue

Pointers & Memory

Question 13, GATE 2017: Printed C source:
#include <stdio.h>
int *assignval(int *x,int val) { *x=val; return x; }
void main() { int *x=malloc(sizeof(int)); if(NULL==x) return; x=assignval(x,0); if(x) { x=(int *)malloc(sizeof(int)); if(NULL==x) return; x=assignval(x,10); } printf("%d\n",*x); free(x); }
Choose A compiler error because malloc lacks a cast; B compiler error because NULL==x must be reversed; C compiles but may leave dangling pointer; D compiles but may leak memory. The missing stdlib.h and void main are literal source issues.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Our answer: D under declared-library interpretation

1. Name the first allocated block A. If its allocation fails the function returns. Otherwise assignval(x,0) changes *x, not x: x still points to A and is nonnull.

2. Thus if(x) is entered even though the integer stored is zero. The second malloc result overwrites x, so no live variable retains A’s address.

3. If allocation B succeeds, printing/freeing uses B only. If it fails, the early return still does not free A. Either way after the second assignment A is leaked. This is intended D, subject to the source-declaration caveat below.

stdlib.h is omitted, so malloc/free lack their required declarations in modern C; void main is not a standard hosted entry point. The intended leak analysis assumes these routine issues are repaired, rather than endorsing option D’s literal “compiles successfully” wording.

Original paper, page 8 · Answer key

1 mark · MCQ
Report issue

Pointers & Memory

Question 14, GATE 2017: Consider C code: void printxy(int x,int y){ int *ptr; x=0; ptr=&x; y=*ptr; *ptr=1; printf("%d,%d",x,y); }. What does printxy(1,1) print? A:0,0. B:0,1. C:1,0. D:1,1.
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Step through it (10 steps)

1. At function entry the local parameter values are x=1,y=1. The assignment x=0 changes x, and ptr=&x makes ptr point to the storage occupied by x.

2. The expression *ptr reads that storage, currently 0, so y=*ptr copies 0 into y. This is a value copy, not a lasting connection between y and x.

3. The next statement *ptr=1 writes into x through the pointer. Now x=1 while y remains 0. The output is 1,0, option C. C function arguments are passed by value; the original call literals do not constrain these local assignments.

Original paper, page 6 · Answer key

2 marks · NAT
Report issue

Pointers & Memory

Question 55, GATE 2017: C program includes stdio.h and string.h, then executes char *c="GATECSIT2017"; char *p=c; printf("%d",(int)strlen(c+2[p]-6[p]-1));. What output is intended, and what caveat applies to the printed expression?
Tap to enlarge
Answer & solution

Official answer: 2.0

Our answer: 2 under intended character-offset arithmetic; strict C undefined behavior

1. C defines a[b] as *(a+b), so 2[p]=p[2] and 6[p]=p[6]. In the string, these are T and I. Under ASCII-compatible character values, T-I-1=84-73-1=10.

2. If this integer offset is computed before pointer addition, c+10 points to the suffix "17" of GATECSIT2017. strlen then returns 2, and the explicit cast to int matches the %d format. This explains the official intended numerical answer.

3. Strictly, however, the printed additive expression is left-associative: ((c+2[p])-6[p])-1. Its first addition forms c+84, far outside the string object (12 characters plus its terminator). C does not allow that intermediate out-of-bounds pointer arithmetic, even if later subtraction would return to a valid offset. The printed program therefore has undefined behavior rather than a guaranteed output.

4. Writing c+(2[p]-6[p]-1) would avoid that intermediate-pointer problem under the intended encoding. The answer 2 additionally assumes an encoding giving the specified T-I difference; C does not require alphabetic characters to have ASCII codes. Preserve both the official intended answer and the strict-C/encoding caveat.

Original paper, page 22 · Answer key

1 mark · NAT
Report issue

Pointers & Memory

Question 15, GATE 2016: Find the printed value in this C program (stdio.h is included):
void mystery(int *ptra,int *ptrb){int *temp;temp=ptrb;ptrb=ptra;ptra=temp;}
int main(){int a=2016,b=0,c=4,d=42;mystery(&a,&b);if(a<c)mystery(&c,&a);mystery(&a,&d);printf("%d\n",a);}
Tap to enlarge
Answer & solution

Official answer: 2016.0 : 2016.0

Our answer: 2016

mystery swaps only its local pointer parameters; it never writes through either pointer. All pointed-to integers remain unchanged and the conditional a<c is false. The printed a is 2016.

C passes the pointer values by value, producing local copies of the addresses. Changing which address ptra or ptrb contains does not modify a,b,c or d. To swap integers the function would need assignments through *ptra and *ptrb; to swap caller pointer variables it would need a different interface. After the first call a remains 2016, so 2016<4 is false. The final call likewise has no effect on a before printing.

Original paper, page 8 · Answer key

2 marks · MCQ
Report issue

Pointers & Memory

Question 62, GATE 2015: Assume x address=2000 decimal and unsigned int occupies four bytes. Code: int main(){unsigned int x[4][3]={{1,2,3},{4,5,6},{7,8,9},{10,11,12}};printf("%u, %u, %u",x+3,*(x+3),*(x+2)+3);}. A 2036,2036,2036; B 2012,4,2204; C 2036,10,10; D 2012,4,6.
Tap to enlarge
Your answer
Answer & solution

Official answer: A

Our answer: A under intended address display; literal printf has undefined behavior

x decays to a pointer to a whole three-element row, so adding 3 advances 3×12 bytes. Dereferencing that pointer produces a row array, which decays to its first-element pointer rather than the value 10. By contrast *(x+2)+3 adds three four-byte elements to the third row's base2024, again yielding numerical address 2036, now one past that row. These address calculations explain intended A only. Printing pointers with %u is a variadic type mismatch and undefined behavior; there is no guaranteed actual C output.

Solution: Each row occupies 3*4=12 bytes. x+3 points to the fourth row at 2000+36=2036; *(x+3) decays to that row’s first element at 2036. *(x+2)+3 is the valid one-past pointer of the third row, also numerically 2036 under the stated layout. Thus the intended address triple is 2036, 2036, 2036, A. However all three arguments are pointers while %u requires unsigned int; this variadic format mismatch is undefined behavior in C. A conforming address display uses %p with each pointer cast to void*, whose textual format is implementation-defined. The omitted stdio declaration is another standalone-code caveat.

Original paper, page 23 · Answer key

2 marks · NAT
Report issue

Pointers & Memory

Question 43, GATE 2015: What is the intended printed output of this C program? Also distinguish that output from its portability limitation.
#include <stdio.h>
int main() { static int a[]={10,20,30,40,50}; static int *p[]={a,a+3,a+4,a+1,a+2}; int **ptr=p; ptr++; printf("%d%d",ptr-p,**ptr); }
There is no separator between the two decimal conversions.
Tap to enlarge
Answer & solution

Official answer: 140

Our answer: 140 under compatible printf type convention

1. After ptr++, ptr=p+1, so ptr−p=1 and **ptr=*(a+3)=40.

2. The adjacent decimal conversions produce 140. Pointer subtraction has type ptrdiff_t, which need not be int; %d is portable only when its promoted type is int. Otherwise the format mismatch is undefined behavior. Use %td for ptr−p, or cast this known-small difference to int, to guarantee the intended display.

Original paper, page 68 · Answer key

1 mark · MCQ
Report issue

Pointers & Memory

Question 10, GATE 2014: Consider the C program with stdio included: main(){ int i; int *pi=&i; scanf("%d",pi); printf("%d\n",i+5); }. Which statement is true? A: Compilation fails. B: A runtime error occurs. C: It prints five more than the address of i. D: It prints five more than the integer entered. Interpret the legacy main declaration under the intended historical C convention.
Tap to enlarge
Your answer
Answer & solution

Official answer: D

Our answer: D under the intended C execution assumptions

1. Method and setup. The address operator makes pi point to the existing integer object i. scanf requires precisely such a destination pointer for %d, so this is equivalent to passing &i. printf subsequently evaluates the integer expression i+5; it does not use the pointer’s numeric address.

2. Work through the result and its assumptions. pi is a valid pointer to i, so a successful scanf conversion stores the entered integer in i and printf displays i+5, D. Assume representable input and no signed overflow; the source also uses legacy implicit-int main syntax rather than modern int main(void). These routine source conventions matter for literal compilation.

Original paper, page 9 · Answer key

1 mark · MCQ
Report issue

Pointer arithmetic in string output

Pointers & Memory

Question 22, GATE 2011: What does this literal C fragment print? The initial capital in Char is as printed.
Char c[] = "GATE2011";
char *p = c;
printf("%s", p + p[3] - p[1]);

(A) GATE2011
(B) E2011
(C) 2011
(D) 011
Tap to enlarge
Your answer
Answer & solution

Official answer: C

Our answer: C only under intended offset arithmetic; literal C is not well-defined

Using ASCII arithmetic, E−A=4, so the intended pointer is c+4 and the intended suffix is 2011, C. But p+p[3]−p[1] associates as (p+p[3])−p[1]. Its first pointer operation forms p+69 in ASCII, far beyond the 9-byte array, causing undefined behavior before the subtraction returns to offset 4. The source also capitalizes Char, which is not the C keyword char unless separately defined. Replacing Char with char and writing p+(p[3]−p[1]) repairs the intended calculation, still with an explicit character-encoding assumption. The official result is not a guarantee of the literal fragment.

Index the intended string: c[0]='G', c[1]='A', c[2]='T', c[3]='E', c[4]='2', c[5]='0', c[6]='1', c[7]='1', c[8]='\0'. A valid pointer to c[4] makes %s print characters until c[8], producing 2011. This explains the examiner's arithmetic but must not erase the separate language-law issues in the literal source. Pointer arithmetic has validity requirements at every intermediate operation, not only at the final address.

Original paper, page 5 · Answer key

1 mark · MCQ
Report issue

Pointer parameters passed by value

Pointers & Memory

Question 11, GATE 2010: What does this C program print?
#include <stdio.h>
void f(int *p, int *q) { p=q; *p=2; }
int i=0, j=1;
int main(void) { f(&i,&j); printf("%d %d\n",i,j); return 0; }
Options: (A) 2 2; (B) 2 1; (C) 0 1; (D) 0 2.
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

Initially i=0 and j=1. The local parameter assignment p=q redirects p to j, without altering i or the caller’s pointer arguments. Then *p=2 writes j=2. The printed values are 0 2, option D.

C passes the pointer values by value. At entry p contains &i and q contains &j; p=q copies &j into the local pointer p. It does not copy j into i. The later dereference acts on the new pointee j. Distinguish p=q, which redirects a pointer, from *p=*q, which would copy an integer.

Original paper, page 3

2 marks · MCQ
Report issue

Moving the last linked-list node first

Pointers & Memory

Question 36, GATE 2010: Complete this C function so it moves the last node of a singly linked list to the front and returns the new head.
typedef struct node { int value; struct node *next; } Node;
Node *move_to_front(Node *head) {
 Node *p,*q;
 if(head==NULL || head->next==NULL) return head;
 q=NULL; p=head;
 while(p->next!=NULL) { q=p; p=p->next; }
 /* BLANK */
 return head;
}
Options: (A) q=NULL; p->next=head; head=p;; (B) q->next=NULL; head=p; p->next=head;; (C) head=p; p->next=q; q->next=NULL;; (D) q->next=NULL; p->next=head; head=p;.
Tap to enlarge
Your answer
Answer & solution

Answer: D (no official key was published)

At loop exit p points to the last node and q to its predecessor. First set q->next=NULL to detach p, then p->next=head to link p before the old first node, and finally head=p. This is option D. Updating head before p->next would lose the old head and can create a self-loop; the early return already handles lists shorter than two nodes.

For A→B→C, the loop ends with p=C and q=B. Detach B→C, point C→A and set head=C, obtaining C→A→B→NULL. Choice A only clears the local variable q and leaves B linked to C, producing a cycle. Choice B makes C point to itself. Choice C loses the old head connection by linking the last node to its predecessor instead.

Original paper, page 9

2 marks · MCQ
Report issue

Aliased pointer updates and a value parameter

Pointers & Memory

Question 60, GATE 2008: What does this historical C program print?
int f(int x, int *py, int **ppz) {
 int y,z;
 **ppz += 1; z=*ppz;
 *py += 2; y=*py;
 x += 3;
 return x+y+z;
}
void main() {
 int c,*b,**a;
 c=4; b=&c; a=&b;
 printf("%d",f(c,b,a));
}

(A) 18
(B) 19
(C) 21
(D) 22
Tap to enlarge
Your answer
Answer & solution

Answer: B only if z=*ppz is repaired to z=**ppz; no portable numeric answer as printed (no official key was published)

1. The scan prints **ppz += 1; z = *ppz; with only one dereference in the assignment to z. Since ppz has type int **, *ppz is an int * rather than the integer value of c. Assigning that pointer to int z violates the standard C simple-assignment constraints and requires a diagnostic. Consequently the printed program has no portable numeric answer among the options; accepting it as an extension does not make z equal to 5.
2. If the apparent typo is explicitly repaired to z = **ppz, the intended alias trace is: x starts as a separate copy 4; **ppz += 1 makes c=5 and z=5; *py += 2 makes c=7 and y=7; x += 3 makes x=7. The sum is then 7+7+5=19, option B only for that repaired program.
3. The source also uses historical void main() and omits the stdio declaration. Those conventions do not remove the single-dereference defect. The derived answer is therefore conditional: B applies only after the stated repair, and no listed portable answer is justified for the printed code. No official key is available.

Original paper, page 12

2 marks · MCQ
Report issue

Arithmetic swap with pointer aliasing

Pointers & Memory

Question 57, GATE 2006: C code:
void swap(int *px,int *py) {
 *px=*px-*py;
 *py=*px+*py;
 *px=*py-*px;
}
Statements: S1 compilation error; S2 may cause a segmentation fault for some arguments; S3 correctly swaps for all pointers to accessible integers; S4 correctly swaps for some but not all valid input pointers; S5 may add/subtract integers and pointers. Which statements are intended to be true?
Options:
(A) S1
(B) S2 and S3
(C) S2 and S4
(D) S2 and S5
Tap to enlarge
Your answer
Answer & solution

Answer: C (no official key was published)

1. The code uses *px=*px−*py; *py=*px+*py; *px=*py−*px. For distinct valid integer objects and arithmetic without signed overflow, initial values x,y become x−y,y then x−y,x then y,x, correctly swapping.

2. If px=py, the first assignment zeroes the shared object and the result is not a swap unless it was zero. Invalid pointers may cause a segmentation fault.

3. Thus S2 and S4 are the intended statements: C. No pointer arithmetic occurs, and there is no intrinsic compilation error.

4. Signed overflow is an additional undefined-behavior limitation even with distinct accessible objects.

5. Teaching check: Aliasing is decisive: if px and py point to the same nonzero integer, the first subtraction writes zero and destroys the original value. With distinct valid cells the algebraic swap works only when each intermediate signed operation is representable. Dereferencing an invalid pointer is a further separate risk.

Original paper, page 8

1 mark · MCQ
Report issue

Assignable array and pointer expressions

Pointers & Memory

Question 2, GATE 2003: Given int *A[10], B[10][10]; consider I. A[2], II. A[2][3], III. B[1], IV. B[2][3]. Which expressions can be left-hand sides of assignments without compile-time errors, assuming type-compatible right-hand sides? A. I, II and IV only; B. II, III and IV only; C. II and IV only; D. IV only.
Tap to enlarge
Your answer
Answer & solution

Answer: A (no official key was published)

1. Resolve the declarations before considering assignment: A[i] has type int*, while B[i] has array type int[10]. Applying another subscript dereferences an element and yields int in either case. Arrays are not modifiable lvalues, but pointer objects and int objects are. No actual dereference safety can be inferred from these declarations alone.

2. A is an array of 10 pointers to int. A[2] is an assignable pointer object, and A[2][3] is an assignable int lvalue if the pointer identifies suitable storage. B[2][3] is likewise an int lvalue. B[1] is an array row and cannot be assigned as a whole in C. Thus I,II,IV, option A, with type-compatible right-hand sides; compile-time validity does not establish safe runtime initialization.

Original paper, page 1

2 marks · MCQ
Report issue

Pointer lifetime and initialization errors

Pointers & Memory

Question 2.18, GATE 2001: Three C functions return int pointers. P1 returns &x for automatic local int x=10. P2 declares uninitialized int *px, stores *px=10, then returns px. P3 allocates sizeof(int) with malloc, stores 10 through the pointer, and returns it. Which have pointer problems: only P3; P1/P3; P1/P2; all three? Distinguish the intended successful-allocation model from failure handling.
Question 2.18, GATE 2001: Three C functions return int pointers. P1 returns &x for automatic local int x=10. P2 declares uninitialized int *px, stores *px=10, then returns px. P3 allocates sizeof(int) with malloc, stores 10 through the pointer, and returns it. Which have pointer problems: only P3; P1/P3; P1/P2; all three? Distinguish the intended successful-allocation model from failure handling.
Tap to enlarge
Your answer
Answer & solution

Answer: C under successful allocation for P3 (no official key was published)

Step 1: P1 returns the address of an automatic local int. Its lifetime ends when the function returns, so the returned pointer cannot be used to access that former object.

Step 2: P2 declares an uninitialized pointer and immediately writes through it. No valid target object has been established, causing undefined behavior.

Step 3: P3 allocates sizeof(int), writes 10 into the allocated object, and returns its pointer. Successfully allocated storage remains alive until freed, even after the function returns. Thus the intended contrast is P1 and P2, C.

Practical qualification: P3 must check malloc’s result before dereferencing it and the caller must eventually free it. If allocation fails, the unchecked P3 is also erroneous; appropriate declarations/headers are assumed.

Original paper, page 6

1 mark · MCQ
Report issue

Matching pointer errors to code

Pointers & Memory

Question 1.12, GATE 2000: Classify X: m=malloc(5);m=NULL; Y: free(n);n->value=5; Z: char *p;*p='a'. Categories: 1 dangling-pointer use,2 uninitialized-pointer use,3 lost memory.
Tap to enlarge
Your answer
Answer & solution

Answer: D: X3,Y1,Z2 (no official key was published)

Step 1: In X, assigning NULL over the sole saved address of a successful allocation loses the ability to free/access that block, creating lost memory or a leak:3.

Step 2: In Y, free ends the allocated object’s lifetime; the later dereference uses a dangling pointer:1. In Z, an uninitialized pointer has not been made to point at valid writable storage, so dereferencing it is an uninitialized-pointer error:2.

The mapping X3,Y1,Z2 is D. Successful allocation, no second saved reference, and initially valid n are the conventional premises for the first two examples.

Original paper, page 2