assigning a string to another string

后端 未结 5 1009
没有蜡笔的小新
没有蜡笔的小新 2021-01-28 09:11

Why this code is not running? Why str1 is not assigned to str2 ?? I know i have an option of using strcpy but i wish to know the reason why this is not working??



        
5条回答
  •  深忆病人
    2021-01-28 09:35

    You need to do

    strcpy (str2, str1)

    you need to copy each element of the str1 to str2 character by character.

    What you are doing is to attempt assign the address of the string in str1 assign to the array var str2 which is not allowed. Static arrays couldn't be used to be assigned values.

    Even if you had char *str2; and then str2 = str1 although your code would work, but in such a case the string is not copied, instead the address of the string in str1 is copied in str2 so now dereferencing str2 will point to the string

    Also note that when you copy string into a char *str2 always allocate enough memory before copy. one possibility is:

    str2 = malloc (sizeof (char) * (strlen (str1) + 1));
    strcpy (str2, str1);
    

提交回复
热议问题