0

I am new in C i am create a program which will read input parameter from command line and then it will do the comparison, but when i am trying to compile the code i am getting error "warning: initialization makes integer from pointer without a cast" .

I found many example on stack overflow for this error but i am unable to relate the issue in my code . Below is the sample code :

void validateGuess(int guess) {
    if (guess < 555) {
        printf("Your guess is too low.");
    } else if (guess > 555) {
        printf("Your guess is too high.");
    } else {
        printf("Correct. You guessed it!");
    }
}

int main(int argc, int** argv) {
   int arg1 = argv[0];
    validateGuess(arg1);
}

Below error i am getting :

test.c: In function ‘main’:
test.c:14: warning: initialization makes integer from pointer without a cast
2
  • 1
    Don't use argv[0] that's the path of the binary. argv[1] will have a string with the actual argument. Use atoi() to convert it to a number. Commented Sep 14, 2018 at 20:13
  • argv[0] is not an int. It is a string pointer to the executable file name. The first user argument is argv[1] but that too is a string pointer. You need to convert that textual input into an integer variable. Commented Sep 14, 2018 at 20:13

2 Answers 2

1

The program arguments are presented to main as strings, which in C are conveyed via (char) pointers. Although it is allowed to convert pointers to integers, the language requires such conversions to be performed explicitly, via a cast operator. Some compilers will perform such conversions implicitly, however, as an extension. Yours is doing this, but presenting a warning because that might not be what you really wanted.

And indeed it is not what you really wanted. Converting the pointer to an integer is not at all the same thing as parsing the content of the string to which it points. The latter appears to be what you're after, and for that you need to engage an appropriate standard library function, such as strtol(), atoi(), or even sscanf().

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

Comments

0

There are no automatic conversions between numeric and string types in C. Program arguments are strings. Use conversion functions like atoi or strtol

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.