I've decided to complicate my life by learning C. Currently I am trying to fully understand pointers.
So far this is what I understand:
#include <stdio.h>
int main() {
char var = 'A';
// Iniialize a pointer variable to the ADDRESS of variable "var"
char *ptr = &var;
printf("%c", var); // Output: 'A'
// Change the VALUE at the memory location of variable "var"
*ptr = 'B';
printf("%c", var); // Output: 'B'
return (0);
}
But then I was looking into re-assigning a string to a variable, and came across this post, where a pointer variable is assigned a value directly.
This is what I am trying to understand:
#include <stdio.h>
int main() {
// Declare a pointer variable
char *ptr;
// Assign a VALUE directly to a memory location???
ptr = "String 1";
printf("%s", ptr); // Output: "String 1"
return (0);
}
Also, if I assign a new string value to ptr, such as ptr = "String 2";, and also output the memory location after each assignment, I get a different memory location:
#include <stdio.h>
int main() {
// Declare a pointer variable
char *ptr;
// Assign a VALUE directly to a memory location???
ptr = "String 1";
printf("%s\n", ptr); // Output: "String 1"
printf("%p\n", ptr); // Output: 0000000000404003 <- one memory location
// Assign a new VALUE to the pointer variable
ptr = "String 2";
printf("%s\n", ptr); // Output: "String 2"
printf("%p", ptr); // Output: 000000000040400F <- a new memory location
return (0);
}
Am I really assigning a VALUE to the memory location the pointer variable is referencing?
Why does the memory location change when I assign a new value to the pointer variable?