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
Your problem is the line
I believe
NULLis usually defined as(void *) 0, which is a pointer. You’re assigning this pointer to anintvariable, which gives you the error.However, there’s no need to initialize
fromArgvin this case. You can just do:or even just
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 yourif (argc != 2)test before the assignment offromArgv.