What will the following C program print?
TCS aptitude question, verified with a worked answer. Free to practise - no sign-up.
What will the following C program print?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void myfunc(char** param) {
++param;
}
int main() {
char* string = (char*)malloc(64);
strcpy(string, "hello_world");
myfunc(&string);
myfunc(&string);
printf("%s\n", string);
free(string);
return 0;
}
Show answer & explanation
The function 'myfunc' receives a copy of the address of the pointer 'string'. Incrementing 'param' inside the function only modifies the local copy of the double pointer, not the actual pointer 'string' in the main function.
Step-by-step Derivation:
Step 1: In main(), 'string' is a pointer to a heap-allocated memory block containing 'hello_world'.
Step 2: The call 'myfunc(&string)' passes the address of the pointer 'string' (a char**).
Step 3: Inside 'myfunc', the parameter 'param' is a local variable that holds the address of 'string'.
Step 4: The operation '++param' increments the local variable 'param'. This means 'param' now points to the memory location immediately following the 'string' pointer in the stack, but it does NOT dereference 'param' to change the value of 'string' itself (which would require '*param = *param + 1').
Step 5: Since the original pointer 'string' in main() remains unchanged, the printf statement prints the original string 'hello_world'.