Reputation: 125
For example, if I have:
char arr[] = "this is a test";
but I decided I wanted to shrink it by 5 so I do:
arr = &arr[5]:
I tried this out and it seemed to work fine, Im just wondering if this would lead to any undefined behavior or "memory issues".
Upvotes: 2
Views: 142
Reputation: 31409
No, this code would not even compile. It gives this error message:
error: assignment to expression with array type
arr = &arr[5];
^
What you could do is this:
char arr[] = "this is a test";
char *ptr = arr;
printf("Before: %s\n", ptr);
ptr = &arr[5];
printf("After: %s\n", ptr);
If this is a good idea or not depends on the situation. Since arrays are allocated on the stack it's pretty safe. It will not lead to memory leaks.
Here is an interesting twister on the subject. How about writing this?
char * arr = "this is a test";
Then you have a pointer and no array, right? Well, this code does indeed allow you to perform the reassignment arr = &arr[5]
. However, this is NOT equivalent to this:
char str[] = "this is a test";
char * arr = malloc(strlen(str));
strcpy(arr, str);
It is instead equivalent to this:
static char _unnamed_[] = "this is a test";
char * arr = _unnamed_;
One difference between these two is if you are returning arr
from a function. Another is if you are calling free
on it.
Arrays vs pointers
In a comment to your post you "thought that an array name was essentially identical to a pointer", which is wrong. It is very easy to make this mistake, and I have done it thousands of times, and I have had my fair share of humble pie here at SO on that matter. But arrays are not pointers. However, an array does in many cases decay to a pointer, which is exactly what's happening on the line char *ptr = arr
above.
There are many questions with enlightening answers about this. Here is two:
What is the difference between char array vs char pointer in C?
Actually, the array decaying to a pointer is also what's happening on the line ptr = &arr[5]
. According to the definition of the []
operator, this is the same as writing ptr = &(*(arr + 5))
Upvotes: 5