Reputation: 171
First,I have to say that I am new to C programming. What I'm trying to do is write a program that takes an argument input and converts it into an integer and then returns its value. My code looks like this:
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
int fromArgv = NULL; /* holds value from argv[1] */
fromArgv = atoi (argv[1]); /* convert argv[1] to int */
/* if incorrect no. of arguments entered */
if (argc != 2) {
fprintf (stderr, "error: wrong number of arguments\n");
exit (EXIT_FAILURE);
}
return fromArgv;
}
I get the following error when trying to compile:
ex1.c: In function ‘main’:
ex1.c:6:18: error: initialization makes integer from pointer without a cast [-Werror]
cc1: all warnings being treated as errors
Upvotes: 0
Views: 148
Reputation: 9661
As mentioned by others, you are initializing an integer with a "null pointer" (that from a type point of view is a pointer), which is wrong. You wanted to initialize it to zero,
int fromArgv = 0;
Then, you should pick the argument and convert it to int after and not before checking the number of arguments. So, you should move the "atoi" line after the if (argc != 2)
part.
Consider also the possibility to use strtol
instead of atoi
. The former allows you to check if the conversion succeeded.
Upvotes: 1
Reputation: 23699
NULL
is a null pointer constant , and you attempt to assign it to an integer value (fromArgv
), therefore your compiler reports a warning.
The following initialization works fine:
fromArgv = 0;
Although, it is useless, since you are modifying the value of your variable on the next line:
int fromArgv = atoi(argv[1]);
By the way, it is a bad idea to return this kind of value from main
(it is often reserved to error codes), and you are cbecking the number of arguments too late.
Upvotes: 3
Reputation: 95
Why do you ever have to initialize fromArgv ?
just
int fromArgv = atoi(arg[1]);
should be working fine
Upvotes: 0
Reputation: 27095
Your problem is the line
int fromArgv = NULL;
I believe NULL
is usually defined as (void *) 0
, which is a pointer. You're assigning this pointer to an int
variable, which gives you the error.
However, there's no need to initialize fromArgv
in this case. You can just do:
int fromArgv; /* holds value from argv[1] */
fromArgv = atoi (argv[1]); /* convert argv[1] to int */
or even just
int fromArgv = atoi (argv[1]); /* convert argv[1] to int */
What you do have to do, however, is make sure argv[1]
exists before you access it so you don't get a segfault if the user does not enter any command-line arguments. You should move your if (argc != 2)
test before the assignment of fromArgv
.
Upvotes: 5
Reputation: 947
u cant initialize fromArgv to NULL because NULL is a pointer and u are assigning it to int just change the line as int fromArgv ;
Upvotes: 0