How to assign value to a pointer?
With one of the assignment operators, of course. Typically the simple assignment operator (=
), but plussignment (+=
) and minussignment (-=
) can also be used under some circumstances.
I have a char pointer and i give it a value.
In fact, you give it two different values, one after the other. First, with
str = (char*)malloc(4);
you give it a value that points to your four-byte dynamically allocated space. Note that the cast is unnecessary in C and considered poor style by many.
Then, with
str = "abc";
, you assign it a different value, losing the previous one and therefore leaking memory. You are assigning a value to the pointer, not modifying the data to which it points.
You have several alternatives for modifying the pointed-to memory.
You can assign directly via the pointer and related ones (not forgetting the string terrminator!):
*str = 'a';
*(str + 1) = 'b';
// etc.
Equivalently to the previous, you can use indexing syntax
str[0] = 'a';
str[1] = 'b';
// etc.
You can perform a block copy with the memcpy()
or memmove()
function:
memcpy(str, "abc", 4);
For C strings in particular, such as yours, there are functions specific to this purpose, the common being strcpy()
:
strcpy(str, "abc");
Note that strcpy
expects the source to be null terminated, which all string literals are, but some other character arrays are not.
In a next step i want to change the first letter.
Your syntax is correct for that, but you may not modify a string literal. That's what your original code is trying to do, because that's your second assignment causes str
to point to the literal "abc"
.
Overall, do not confuse a pointer with the object to which it points.