int x = 0;
x = 42;
The end result is exactly the same as
int x = 42;
without going through 0
first.
Pointers are not magical.
char* string = malloc(...);
string = "testing";
The end result is exactly1 the same as
char* string = "testing";
without going through malloc
first.
A string is not a pointer. A string is an null-terminated array of characters. In order to allocate a string, you:
- Allocate an array of characters of suitable length.
- Copy a null-terminating sequence of characters to said array (which is entirely different from copying a pointer).
So
// 1 Allocate an array of characters of suitable length
char *string = malloc(strlen("testing")+1);
// note suitable length
// the variable `string` points to the first character of the array just allocated
// 2 Copy a null-terminating sequence of characters to said array
strcpy (string, "testing");
// other ways of copying strings exist
Checking the return value of malloc
is omitted for brevity only.
1 There is some difference: malloc
allocates memory, which the first fragment happily discards, resulting in a memory leak. This difference is, however, undetectable by your program, which means the observable program behaviour is exactly the same. You can only detect the difference from the outside of the program, for example, by tracing it with a debugger.