assigning a string to another string

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

提交回复
热议问题