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;
}
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.
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:
memmove()
(or some other copy mechanism) char**
) 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.
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 .
void strip_quotes(char s[]) {
int len = strlen(s);
if(s[len-1] == '"')
s[--len] = '\0';
if(s[0]=='"')
memmove(s, s+1, len);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.