With c-style strings, how do you assign a char to a memory address that a character pointer points to? For example, in the example below, I want to change num to "123456", so I tried to set p to the digit where '0' is located and I try to overwrite it with '4'. Thanks.
#include <stdio.h>
#include <stdlib.h>
int main()
{
char* num = (char*)malloc(100);
char* p = num;
num = "123056";
p = p+3; //set pointer to where '4' should be
p = '4';
printf("%s\n", num );
return 0;
}
Best Solution
First of all, when you do:
You are not copying the string "123056" to the area of heap allocated by
malloc()
. In C, assigning achar *
pointer a string literal value is equivalent to setting it as a constant - i.e. identical to:So, what you've just accomplished there is you've abandoned your sole reference to the 100-byte heap area allocated by
malloc()
, which is why your subsequent code doesn't print the correct value; 'p
' still points to the area of heap allocated bymalloc()
(sincenum
pointed to it at the time of assignment), butnum
no longer does.I assume that you actually intended to do was to copy the string "123056" into that heap area. Here's how to do that:
Although, this is better practice for a variety of reasons:
If you had just done:
You would have gotten the correct result:
You can contract this operation:
... and avoid iterating the pointer, by deferencing as follows:
A few other notes:
Although common stylistic practice, casting the return value of
malloc()
to(char *)
is unnecessary. Conversion and alignment of thevoid *
type is guaranteed by the C language.ALWAYS check the return value of
malloc()
. It will be NULL if the heap allocation failed (i.e. you're out of memory), and at that point your program should exit.Depending on the implementation, the area of memory allocated by
malloc()
may contain stale garbage in certain situations. It is always a good idea to zero it out after allocation:Never forget to
free()
your heap! In this case, the program will exit and the OS will clean up your garbage, but if you don't get into the habit, you will have memory leaks in no time.So, here's the "best practice" version: