I am new to programming in C and I am trying to write a program that reads in one command-line argument that is the size of an array. I get the error, Thread 1: EXC_BAD_ACCESS (code=1, address=0x0) in Xcode.
int main(int argc, char* argv[])
int size = atoi(argv[1]);
This is a snippet of my program, in which I am using sorting functions with random values, but I need to read in the size of the array first.
Any suggestions?
CodePudding user response:
The "null" value you are getting almost definitely means that you are reading past the end of the argv
array. For example if I run a program as:
myprogram hello world
argc
will be 3argv[0]
will be "myprogram"argv[1]
will be "hello"argv[2]
will be "world"argv[3]
is undefined and you should not even attempt to read the array here! (but will probably be NULL in most environments so that programs crash predictably)
Always check that the index for argv
is less than argc
since array indexes in C start at 0.
CodePudding user response:
the char* argv[] is an array of strings (usually used as char** argv) and the argc is amount of parameter when the 0 parameter is the program name, 1 is first parameter, 2 is second and etc.
you need to check that index of argv (named paramIndexThatIWant) less then argc
for example
#include <stdio.h>
int main(int argc, char** argv)
{
int paramIndexThatIWant = 2; /* param index that i want to use */
if(argc > paramIndexThatIWant )
{
printf("> Param %i equal value %s.\n",paramIndexThatIWant, argv[paramIndexThatIWant]);
}
else
{
printf("No parameter at pos %i, argc is %i\n", paramIndexThatIWant, argc);
}
return 0;
}
again remember that argc count the program name itself as one, so if you have one parameter only so its value will be one, this is why in the example i have just one param, argc equal to 2 but but argv[2] not exist.