Assigning char array a value in C

你。 提交于 2019-12-17 09:55:40

问题


What is the difference between:

char fast_car[15]="Bugatti";

and

char fast_car[15];
fast_car="Bugatti";

Because the second one results with compile error:

error: incompatible types when assigning to type ‘char[15]’ from type ‘char *’

While the first one works fine. Putting a string in array in different place than array initialisation would be helpful.


回答1:


The first is an initialization while the second is an assignment. Since arrays aren't modifiable values in C you can't assign new values to them.

Mind you, you can modify array contents, you just can't say fast_car = .... So the contents are modifiable, the arrays themselves are not.


Using the same symbol = for these widely different concepts is of debatable value.




回答2:


char fast_car[15]="Bugatti";

It says fast_car is an array and be initialized with string the "Buratti". Correct Usage :

char fast_car[15];
fast_car="Bugatti";

The first line is a declaration of char array(not initialized). Second, fast_car here is just an address(a pointer) of the first element in this array of char. The assignment of pointer fast_car to array of char "Buratti" is incorrect by difference type of value.



来源:https://stackoverflow.com/questions/12160233/assigning-char-array-a-value-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!