What happens when a pointer msgPtr which points to a string is assigned the value of a different pointer oldPtr?

Recap

  • A pointer is a variable that contains the address of a variable. Pointers are much used in C, partly because they are sometimes the only way to express a computation, and partly because they usually lead to more compact and efficient code than can be obtained in other ways. Pointers and arrays are closely related;
  • Pointers are used to access memory and manipulate memory addresses.

Now to answer the above question, consider the code below:

#include <stdio.h>

int main(void){
	char *msgPtr = "now is the time";
	char *oldPtr = "old pointer";

	msgPtr = oldPtr;

	printf("msgPtr: %s\n", msgPtr);	
        printf("oldPtr: %s\n", oldPtr);	
	printf("\n\nThe address of msgPtr = %d", *msgPtr);
	printf("\n\nThe address of oldPtr = %d\n", *oldPtr);

	return 0;
}

When you compile and execute the above program it produces the following result on Linux:

Case 1: Without assignment i.e comment line msgPtr = oldPtr

	msgPtr: now is the time
	oldPtr: old pointer


	The address of msgPtr = 110

	The address of oldPtr = 111

Case 1: With assignment i.e uncomment line msgPtr = oldPtr

	msgPtr: old pointer
	oldPtr: old pointer


	The address of msgPtr = 111

	The address of oldPtr = 111

From the above demo, you can see that after the assignment, msgPtr now points to the character array pointed to by oldPtr. They point to the same location.

Add comment


Security code
Refresh