Reputation: 47
I want to copy a string "str" to p . First I used the code I commented out, but the output was empty. So I tried the code that is below the commented area, and it worked. What is the difference between the two methods to manipulate strings in C? Thanks in advance.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char *str = "laekfja";
char *p = (char*)malloc(51 * sizeof(char));
//First try.
/* while(*str)
{
*p++ = *str++;
}
*p = '\0';
printf("%s\n", p);
*/
//Second try.
int i = 0;
while(i < strlen(str))
{
p[i] = str[i];
i++;
}
p[i] = '\0';
printf("%s\n", p);
return 0;
}
Upvotes: 2
Views: 67
Reputation: 4469
Both methods work to copy the string. The error in the first method is in printing the copied string out when the loop is complete:
printf("%s\n", p);
At this point, p
is pointing to the last character inserted into the copy, the null character, not the beginning of the string. So the printf()
correctly prints nothing.
Upvotes: 1