Da Artagnan
Da Artagnan

Reputation: 1199

C I cant printf an integer, which was passed as a argument in command line

I'm trying to printf an integer that was passed by command line but the console print a long random values.

I put this into RUN "C:\Users\pc\Documents\Visual Studio 2013\Projects\Lab3\Debug\Lab3.exe randomString 4"

#include <stdlib.h>
#include <stdio.h>




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

    printf("%s\n", argv[0]); // Working
    printf("%s\n", (argv[1])); // working
    printf("%d\n", (int)(argv[2])); // NOT Working
    printf("%d\n", argc); // Working
    system("pause");
    return 0;
}

Upvotes: 0

Views: 71

Answers (2)

Eugene Sh.
Eugene Sh.

Reputation: 18331

The argv[2] variable is a string pointer (char* to be precise). So casting it to int will just give you the numerical value of this pointer (or part of it, depending on the size of the addresses on your system). And this is exactly your "random long number" that you are seeing. In order to convert the string to a number you can use functions like atoi.

Upvotes: 2

OldProgrammer
OldProgrammer

Reputation: 12169

You can't just "cast" a char* pointer to an int and expect it to be magically converted. That is just printing the address of the first element of the array. You need to convert it to an int with a runtime function such as atoi(argv[2]) See function details here

Upvotes: 4

Related Questions