1

How can I read triples of numbers from the program arguments into an array of integers and then display them? That is I enter ./read 1,2,3 4,5,6 7,8,9 and the ouptput should be

1 2 3

4 5 6

7 8 9

My code works well only for strings, but not integers

#include <string.h>
#include <stdio.h>

int main(int argc, char **argv)
{
  int i;
  int d[argc][3];
  int x[3];
  for(i = 1; i < argc; i ++){
      char *a[3];
      int j = 0;
      a[j] = strtok(argv[i], ",");
      while(a[j] != NULL){
        a[++j] = strtok(NULL, ",");
        x[j] = atoi(&(a[j]));
      }
      printf("%s %s %s \n", a[0], a[1], a[2]);
      printf("%d %d %d \n", x[0], x[1], x[2]);
    }
    return 0;
} 

It displays 1 0 0 on each line.

7
  • 1
    Note: , between 3,4, but not 6 7. Commented Jan 12, 2016 at 20:10
  • What's the purpose of int d[argc][3];? Commented Jan 12, 2016 at 20:10
  • 2
    x[j] = atoi(a[j]); then a[++j] = strtok(NULL, ","); Commented Jan 12, 2016 at 20:11
  • 2
    also a[3] is out of bounds. Commented Jan 12, 2016 at 20:20
  • 1
    when strtok() fails, then this line: x[j] = atoi(&(a[j])); (which is written incorrectly, it should be; x[j] = atoi(a[j]); will be accessing memory at address 0. This is almost certain to result in a access violation seg fault event. I.E. always check (!=NULL) the returned value from strtok() before de-referencing that value Commented Jan 13, 2016 at 14:49

1 Answer 1

2
  1. Here you have an error

    x[j] = atoi(&(a[j]));
    

    you should not pass the address like that, just

    x[j] = atoi(a[j]);
    

    should work.

  2. You must include stdlib.h

  3. You must check against NULL after strtok(). Or to do it correctly follow this comment by @BLUEPIXY.

    x[j] = atoi(a[j]); then a[++j] = strtok(NULL, ",");

Enabling compiler warnings should have let you find this yourself.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.