Question

I'm a very inexperienced C learner, and I have been getting a warning in this code, that is supposed to invert the String passed as the first argument of the command when called (programming in Linux Ubuntu).

The warning is: 14:9: warning: assignment makes integer from pointr without cast

    #include <stdio.h>
    #include <string.h>

    int main(int argc, char *argv[]) {

        char str[80];
        int p = 0;
        int i;

        for(i = strlen(argv[1]) - 1; i >= 0; i--){
            str[p] = argv [1][i];
            p++;
        }

        str[p] = "\0";
        printf("%s\n", str);

    }

The code is supposed (and it does with a few unwanted characters) print the inverted string of the first argument when I use the command ./command stringhere.

So as an example, when I use ./invert_string string, the console prints gnirts and a bunch of question marks and other characters. Is there a reason for this? Is the code printing values in the memory it's not supposed to?

Was it helpful?

Solution

The immediate fix for the problem you have seen is changing the nul termination statement to:

str[p] = '\0';

This change is required as you want to assign a char ('\0') and not a char * ("\0").

However, as the source string is nul terminated, you can copy the terminator with the whole string.

In addition, note that if the source string would be longer than 80 chars, you will have a buffer overflow.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top