Reputation: 1788
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?
Upvotes: 0
Views: 415
Reputation: 34575
You say "I don't initialize the char pointer". You do, with
new_c = c;
The array c
decays to a pointer, just as if you had passed c
directly to printf
. And then it is printf
which iterates through the array until the zero terminator is found.
Upvotes: 1
Reputation: 364
Run this program and you will get a clear picture of what is happening
#include <stdio.h>
#include <string.h>
int main(void) {
char c[10] = "something";
char *new_c = NULL;
char new_c_2[10] = "";
new_c = c; // copies address of 'c' to 'new_c'
for(int i=0; c[i]!='\0'; i++) {
new_c_2[i] = c[i]; // copies value of 'c' to 'new_c_2'
}
// Data before changing the value of 'c'
printf("\nData before changing the value of \'c\'\n");
printf("new_c = %s\n", new_c);
printf("new_c_2 = %s\n", new_c_2);
strcpy(c, "changed");
// Data after changing the value of 'c'
printf("\nData after changing the value of \'c\'\n");
printf("new_c = %s\n", new_c);
printf("new_c_2 = %s\n", new_c_2);
return 0;
}
OUTPUT:
Data before changing the value of 'c'
new_c = something
new_c_2 = something
Data after changing the value of 'c'
new_c = changed
new_c_2 = something
char *new_c = NULL; new_c = c;
These statements are just pointing 'new_c' to the address of 'c'. So, if you change the value of 'c', and use 'new_c' it will go to the address of 'c' and give the updated value.
We copy the string into another so that we can use the old value even if we change the value of 'c'.
Please refer to call by value and call by reference in C programming for further details.
Upvotes: 3
Reputation: 140256
Why do people even bother iterating through the entire array to copy?
well, maybe to be sure the original reference isn't deleted/overwritten after a while.
For instance, if the original buffer is a local/automatic variable, which will be invalid after returning from the function.
Or if I just do c[0] = '\0';
. new_c
doesn't display a thing now because I just killed the only copy of the string.
Both copy & referencing another string through a "shallow" pointer are useful, depending on the use cases.
Upvotes: 0