本文介绍了指针与字符的类型不兼容。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我有这样的事情: #include< stdio.h> main() { struct line { char write [20]; char read [20]; struct line * next; }; struct line n1; n1.write =" concepts" ;; } 但是,如果我尝试编译它,我得到编译错误说 赋值中的不兼容类型。奇怪的是,如果我设置 写为整数,我不会得到这样的错误并且它编译。 特殊的东西需要用字符串和指针来完成吗? 谢谢。I have something like this:#include <stdio.h>main (){struct line{char write[20];char read[20];struct line *next;};struct line n1;n1.write= "concepts";}However, if i try to compile it, i get a compiler error saying that"incompatible types in assignment". Whats strange is that if i setwrite as an integer, i don''t get such a error and it compiles. Doessomething special need to be done with character strings and pointers?Thanks.推荐答案 它们是不同的。你已经声明写为20个字符的数组和 你试图为它指定一个指向const char的指针。 我觉得你很困惑通过指针访问数组 并分配给数组。你必须将字符串文字复制到 数组中。 - Ian Collins。They are different. You have declared write as an array of 20 char andyou are attempting to assign a pointer to const char to it.I think you are confused regarding accessing an array through a pointerand assigning to an array. You have to copy the string literal into thearray.--Ian Collins. 这可能是围绕数组和指针的常见混淆。你 不能处理数组好像这是 作业左侧部分的指针。数组名称衰变 to pointers(到他们的第一个元素) 当他们在作业的正确部分,但反过来不是 true。 您必须使用strncpy()或strlcpy()将 常量字符串中的数据复制到结构的数组成员中,即: size_t len; len = sizeof(n1.write); strncpy(n1.write," concepts",len - 1); n1.write [len - 1] =''\ 0''; 或 strlcpy(n1.write," concepts",sizeof(n1.write));This is probably the usual confusion around arrays and pointers. Youcannot treat an array "as if" it was a pointer in the left part of anassignment. Array names "decay" to pointers (to their first element)when they are in the right part of an assignment, but the reverse is nottrue.You will have to use strncpy() or strlcpy() to copy the data from yourconstant string into the array member of the structure, i.e. with:size_t len;len = sizeof(n1.write);strncpy(n1.write, "concepts", len - 1);n1.write[len - 1] = ''\0'';orstrlcpy(n1.write, "concepts", sizeof(n1.write)); < http://www.c-faq.com/>。阅读第6节阵列和指针的全部内容。 - Keith Thompson(The_Other_Keith) ks *** @ mib.org < http://www.ghoti.net/~kst> 圣地亚哥超级计算机中心< *> ; < http://users.sdsc.edu/~kst> 我们必须做点什么。这是事情。因此,我们必须这样做。<http://www.c-faq.com/>. Read all of section 6, "Arrays and Pointers".--Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>We must do something. This is something. Therefore, we must do this. 这篇关于指针与字符的类型不兼容。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
05-27 22:23
查看更多