Warning in C: assignment makes integer from pointer without a cast

时光总嘲笑我的痴心妄想 提交于 2019-12-12 02:57:57

问题


I keep getting this error when compiling my program. This is just a small part of my code, so if needed I will provide the rest of the code. Any ideas on why this is occuring?

void strip_quotes(char s[]) {
   if (s[0]=='"') s=s+1;
   if (s[strlen(s)-2]=='"') s[strlen(s)-2]=NULL;
}

回答1:


As Dave has already correctly pointed out the reason for the compiler error:

 s[strlen(s)-2]=NULL; /* = (void*)0 */

There is another bug in the code that won't cause a compiler error:

if (s[0]=='"') s=s+1;

the increment of s will not be visible to the caller, as C passes by value including pointers (see http://c-faq.com/ptrs/passptrinit.html). Options for correcting:

  • shift the content of the array to the left using memmove() (or some other copy mechanism)
  • pass the address of the pointer (a char**)
  • return a pointer to s

Changing the content of s is preferable as it avoids a possible problem if the array was dynamically allocated: only pointers returned by malloc() (or calloc() and realloc()) can be passed to free(). If the value of s is changed then it cannot be free()d via s.

Note that:

void strip_quotes(char s[]) {

is equivalent:

void strip_quotes(char* s) {

incase you were confused as to were pointers are used in the code.




回答2:


You are setting a character of s to NULL. The proper way to add a null character to a string is to use '\0'.

To explain the message, NULL is likely defined as (void*)0, so when you assign it, you are converting void* to char, hence the warning.




回答3:


Dave got it, but I'll try to add a bit.

NULL is a pointer of type void*, which can be assigned to any pointer type. If you are setting a pointer to a value that can never be used to represent valid memory, use NULL.

'\0', aka NUL, is ascii value 0 and is used to terminate strings. It is of type char. http://www.december.com/html/spec/ascii.html .




回答4:


void strip_quotes(char s[]) {
    int len = strlen(s);
    if(s[len-1] == '"')
        s[--len] = '\0';
    if(s[0]=='"')
        memmove(s, s+1, len);
}


来源:https://stackoverflow.com/questions/16632765/warning-in-c-assignment-makes-integer-from-pointer-without-a-cast

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