0

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;
}
8
  • 3
    why did you write (int)s; ??? Commented May 19, 2013 at 8:34
  • 1
    What are you trying to achieve with the statement (int)s;? Commented May 19, 2013 at 8:34
  • 1
    You may want to change s[strlen(s)-2]=NULL; to s[strlen(s)-2]='\0'; Commented May 19, 2013 at 8:35
  • what are you trying to do? you were casting s to an integer and then trying to set it to null?! Commented May 19, 2013 at 8:35
  • which line has the warning on it according to the compiler? Commented May 19, 2013 at 8:37

4 Answers 4

6

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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.

Comments

0

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 .

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.