I'm currently playing around with passing char array to a char pointer. Lots of the examples I see show how you need to allocate the memory that the string pointer will use before copying the char array to it. And when copying, you iterate through the array to store each address into the allocated char pointer.
In the example below I don't initialize the char pointer and neither do iterate through the array. I just pass the pointer of the first element.
int main()
{
char c[10] = "something";
// char* new_c = (char *)malloc(strlen(c)+1);
char *new_c = NULL;
new_c = c;
printf("%s", new_c);
return 0;
}
Why is new_c still printing the entire string? Why do people even bother iterating through the entire array to copy?
new_c = c;. The arraycdecays to a pointer, just as if you passedcdirectly toprintf. And then it isprintfwhich iterates through the array until the nul terminator is found.