Create 2 int variables ( int1 and int2 ), an int pointer variable ( pInt ), and
ID: 3542667 • Letter: C
Question
- Create 2 int variables (int1 and int2), an int pointer variable (pInt), and a pointer to an int pointer (ppInt).
- Set int1 to 10.
- Set pInt to point to int1 (i.e. set pInt to int1's address).
- Print the value of int1 and the value of the int being pointed to by pInt. They should be the same.
- Increment int1.
- Print int1 and the value of the int being pointed to by pInt. They should both be 1 larger now (11).
- Subtract 20 from the value being pointed to by pInt.
- Print both int1 and the value being pointed to by pInt. They should both be the same (-9).
- Set pInt to point to int2.
- Set the value being pointed to by pInt to 5.
- Print int1, int2, and the value being pointed to by pInt. int1 should be -9 and the other two should be 5.
- Set ppInt to point to pInt.
- Increment the value of int2 through ppInt (i.e. the only variable in the statement is ppInt).
- Print int1, int2, the value pointed to by pInt, and the double indirection of ppInt (i.e. int2, but using ppInt). int1 should still be -9 and the other three should be 6.
Explanation / Answer
#include <stdio.h>
int main()
{
int c[ ]={2.8,3.4,4,6.7,5};
int int1,int2,*pInt,**ppInt;
int1=10;
//setting pointer pInt to point to int1
pInt=&int1;
printf("int1 = %d and pInt points to %d ",int1,*pInt);
//incrementing int1
int1++;
printf("Updated int1 = %d and pInt now points to %d ",int1,*pInt);
//incrementing int1 using pInt
*pInt=*pInt-20;
printf("Updated int1 = %d and pInt now points to %d ",int1,*pInt);
//setting pointer pInt to point to int2
pInt=&int2;
//updating int2 to 5 using pInt
*pInt=5;
printf("int1 = %d, int2 = %d and pInt points to %d ",int1,int2,*pInt);
//setting pointer ppInt to point to pointer pInt
ppInt=&pInt;
//updating int2 using pointer to pointer to int2 i.e ppInt
**ppInt=**ppInt+1;
printf("int1 = %d, int2 = %d and pInt points to %d and the double indirection of ppInt = %d ",int1,int2,*pInt,**ppInt);
}