0

I am trying to strip off the trailing \n char that fgets() appends. I am replacing this character with a string terminating char, \0.

Why is the compiler giving the error: "Assignment makes integer from pointer without cast".

word[strlen(word) - 1] = "\0";

Here's a more complete sample of the code is question in case some context is needed.

FILE *wordFile = fopen("/temp/words.txt", "r");
char word[100];
while (fgets(word, 100, wordFile)) {
    // Strip off the trailing the \n so it is not counted
    // as part of the string length
    word[strlen(word) - 1] = "\0";
    :
}
4
  • 9
    I smell fake code. I bet you wrote "\0" instead of '\0'... Commented Feb 21, 2011 at 2:26
  • HA! I am new to this IDE. Apparently my changes where not saved. I did indeed have "\0" first. I corrected the issue but apparently I was not rebuilding. Commented Feb 21, 2011 at 2:29
  • 1
    If there is no '\n' in your word (say, the input ended with an EOF or reached your buffer size without the '\n'), it'll happily chop off the last character in your word. Commented Feb 21, 2011 at 2:29
  • @sarnold: ah, that's why the C standard says that behavior is undefined if a source file isn't terminated by a newline! So that compilers can use this code ;-) Commented Feb 21, 2011 at 2:32

1 Answer 1

2

Your problem lies with the statement:

word[strlen(word) - 1] = "\0";

This is trying to assign the pointer to the C string to the array element, an integral type char, hence the error message "Assignment makes integer from pointer without cast".

What you should have written was:

word[strlen(word) - 1] = '\0';

which assigns a character to the array element.

As an aside, you should watch out for lines that are longer than (about) 100 characters. You'll only read the first part of the line, it won't have a newline at the end, and you'll read the rest of the line as a separate line next time through your loop (and this may happen many times if you have a line that is, for example 1K long).

For what it's worth, you can fix those problems with code along the following lines:

if ((s = strlen (word)) > 0) {
    if (s[s-1] != '\n') {
        // Line was too long, do something intelligent.
    } else {
        s[s-1] = '\0';
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanys heaps for the edit, @Antti, I can't believe (1) I made such a bone-headed mistake; and (2) no-one's picked it up for the last seven-plus years :-)

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.