I am new to coding in C and had a question about the "assignment to expression with array type" error. From my understanding (correct me if I'm wrong), using char*
in conjunction with malloc()
allocates memory on the heap, which we can read and write to. Using a char var[]
, allocates memory on the stack frame, which we can also read and write to. I thought that these two would be similar to work with, but apparently they are quite different.
Using the code below, I was able to remove the first char in a string on the heap (by incrementing the pointer to the string).
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main(void) {
char* test = malloc(20 * sizeof(char));
strcpy(test, "XHello World!");
test = &test[1];
printf("%s\n", test); // Hello World!
}
Trying to do the same operation with a char var[]
though, I ran into the "assignment to expression with array type" error. My code is below.
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main(void) {
char test[20] = "XHello World!";
test = &test[1]; // assignment to array type error
// test = test + 1 // same error
// test = *(test + 1); // same error
// test += sizeof(char); // same error
printf("%s\n", test);
}
In the above code, I thought that since test
is a pointer, and &test[1]
is also a pointer (just like in the first example), assignment would work the same. Could someone explain why this isn't the case? Any help would be greatly appreciated!
My actual goal was to extract a string from some brackets (eg, [HELLO]
), and I was trying to use the above technique to remove the opening bracket, and test[strcspn(test, ']')] = '\0'
to remove the closing bracket. Maybe this is a bad approach entirely?