Passing argument to a program!!

Hi friends,
I have a small query, hope u will help me with it.
I want to write a small program which would take an integer as an argument, then I want to save that argument in a variable of type int. Could you please help me with it. Here is my program

 
 
#include <stdio.h>
 
int main(int argc, char *argv[])
{
int x;
x = argv[1];
printf("%d\n",argv[1]);
return 0;
}

This program cannot be compiled, it says that there is some problem with type conversion or something. Could you please help me with this thing!

argv[1] is a string (array of char) - you need to convert it to an int before assigning it (e.g. with man atoi ("posix")).

Yes, you see:

char *argv[]

int x;

C is not a scripting language, you can't cavalierly assign a string into an integer and expect to get anything sensible. If you try and force it with typecasting, it will take you completely literally and put the wrong type in, giving you results you didn't expect at best and crashing your program at worst.

How about this:

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

int main(int argc, char *argv[])
{
        if(argc < 2)
        {
                fprintf(stderr, "Not enough arguments\n");
                return(1);
        }

        printf("%d\n", atoi(argv[1]));
        return(0);
}

Thanks buddy, you solved my problem. That was exactly what I was looking for!
Here is what I did according to your suggestion.

x = atoi(arg[1]);

Now, I can do all the operation on that argument
Thanks a ton!

You got it.