0

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?

Daniel
  • 13
  • 3
  • Did you pass a command-line argument? In XCode or similar, it may need to specified in a configuration dialog if running via the tool itself. – nanofarad Dec 03 '21 at 21:18
  • 1
    *Always* check `argc` before accessing `argv`. [what-does-int-argc-char-argv-mean?](https://stackoverflow.com/questions/3024197/what-does-int-argc-char-argv-mean) – Weather Vane Dec 03 '21 at 21:19

2 Answers2

0

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 3
  • argv[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.

slembcke
  • 1,359
  • 7
  • 7
  • I'm still confused on how to check the index for argv is less than argc, but if I go to the Products->Scheme->Edit Scheme->Run->Arguments->Arguments Passed On Launch in Xcode, and enter a value, the program runs fine. Do you have to adjust argc or argv (probably argv) somehow? – Daniel Dec 03 '21 at 22:01
  • No, the C runtime and OS sets up those variables for you based on the parameters passed to your program. As Anton K puts it below, you have to check that the `argv[]` index you want is less than `argc`. – slembcke Dec 05 '21 at 20:25
0

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.

enter image description here

Anton K
  • 109
  • 6