assigning a string to another string

后端 未结 5 1005
没有蜡笔的小新
没有蜡笔的小新 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:13

    str2 is a static array. You can't just reassign it like a pointer.

    As for your pointer example, q=s reassigns q to point to the same space that s is pointing to. However, the pointer reassignment does not copy the value.

    For static arrays, use strcpy() to copy the value. For pointers, use strdup().

    0 讨论(0)
  • 2021-01-28 09:24

    In C you can only assign objects that have type; and in C a string is not a data type. Instead it is a convention - the convention being that strings are represented by null-terminated character arrays; and because arrays are not considered as types, neither are strings.

    In your second code fragment, you have simply made q point to s; this is not a copy of the string at s, but merely a copy of the pointer 's'. They both refer to the same data in memory. So if for example you changed the string at 's', and then printed the string at 'q', you will see that the data at 'q' has also changed. More directly if you did printf( "s:%p, q:%p" (void*)s, (void*)q ) ; you will see that they both hold the same pointer value.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2021-01-28 09:35

    You may also use strdup() which allocates exact amount of space needed to store a copy.

    0 讨论(0)
  • 2021-01-28 09:39

    str2 and str1 refers to the address of their first elments so assignment of arrays is not done in this way use either str[] to assign char by char or use inbuilt strcpy

    0 讨论(0)
提交回复
热议问题