-1

What I am trying to do is to access a string value in a multidimensional string array in C. The string is actually a number value which I want to store in an integer value.

When I try to print the value as following

  printf("TESTING COMMAND\n");
  printf("%d\n",commands[0][0]);

The value prints the normal expected value

However when I try to use it to initialize an array for example as below

  char **options[ (x - 1) ];

This gives the following error

  error: size of array ‘options’ has non-integer type

Which I expect because the command array is declared as following

  char ***commands;

The thing is that even if I try to assign an integer variable to hold this value I get a segmentation error

 x = command[0][0];

I have also tried functions like strtol which led to the same result. However I am not sure if I have used the function right.

Any suggestions ?

int x;
printf("TESTING COMMAND\n");
printf("%d\n",commands[0][0]);
x = command[0][0];
printf("Creating options of size = %d\n", x );
teppic
  • 8,039
  • 2
  • 24
  • 37
Abdelrahman Shoman
  • 2,882
  • 7
  • 36
  • 61

2 Answers2

0

Try the sscanf formatting function.

It works like - void sscanf(char *arr, "format-specifier", address of var to store the formatted value.)

For eg : say we have - char *arr = "123" declare int val;

then- sscanf(arr, "%d", &val); val will equal 123.

-1

The function you're looking for is probably atoi():

x = atoi(commands[0][0]);

It parses the string as a number and returns it as an int. You'll need to include stdlib.h.

Dolda2000
  • 25,216
  • 4
  • 51
  • 92
  • 3
    since `atoi()` has no way of reporting errors, and it invokes undefined behavior upon overflow, its use is discouraged – please do **not** recommend it. A more modern alternative is `strtol()`. – The Paramagnetic Croissant Apr 04 '15 at 00:46
  • 1
    In the vast majority of situations there isn't much reason to care about those shortcomings, however, and it *is* simpler to use. :) – Dolda2000 Apr 04 '15 at 00:47
  • 2
    carelessly ignoring error conditions is unprofessional because it is dangerous. Do not encourage doing it! – The Paramagnetic Croissant Apr 04 '15 at 07:42
  • It's not like it causes security problems, crashing or other reliability issues. It is not necessarily meaningful to report every user mistake in every piece of software. – Dolda2000 Apr 04 '15 at 14:24