Hi,
Is it ok to make a copy of my string like this?
char *s1 = malloc(sizeof(char)*6);
char *s2 = malloc(sizeof(char)*6);
/* do some processing on s1 */
s2 = s1;
or do i need to use that string copy function?
Hi,
Is it ok to make a copy of my string like this?
char *s1 = malloc(sizeof(char)*6);
char *s2 = malloc(sizeof(char)*6);
/* do some processing on s1 */
s2 = s1;
or do i need to use that string copy function?
No, you need to use either strcpy or memset (or even a simple while loop).
What the above does just allocates 6 bytes and then lets it leak, as well, no copying takes place other than address location values.
s1 is a pointer, s2 is a pointer.
If you assign the value of one pointer to another pointer, you've just changed the value of a pointer, not done anything with an array of char's.
In C, why not use strcpy(), to copy a string?
This function, strcpy() should *leap* right out at you as something to use perhaps, to copy a string, automatically; just in a moment ==> strcpy() to copy strings.
I have tried to use strcpy to race homing pigeons, fix engines and tires, and provide marital counseling --> didn't work! Use it to copy strings; it's all it's good for!