HastatusXXI HastatusXXI - 1 month ago 10
Bash Question

Declaring a global CHAR array from shell in C

I have a problem with global variables in C. I have to create an array of strings with C. The number of strings will be determined by the argument passed by the shell (

number_of_string = atoi(argv[1])
). So I think the best way to do this is with an array of
pointers. Every elemnt of this array will point to a section of memory dinamically reserved with malloc. The main problem is that I need to define the size of the array before the execution of main (argv[1] doesn't exist yet), as a global variable. I don't know how I could solve this. Can anyone help me?


Does this address your problem?

#include <stdlib.h>

char **strings;

int main(int argc, char **argv)
    int size;
    int i;
    if ( argc < 2 )
        return 1;

    size = atoi(argv[1]);

    if ( size <= 0 )
        return 2;

    strings = malloc(sizeof(char*)*size);

    for ( i = 0 ; i < size ; i++ ) {
        strings[i] = malloc(sizeof(char)*100);

    // You now have argv[1] 100-byte strings (don't forget about NULL terminators)