Home > Mobile >  Initialise array of character pointers inside a function to be used in main
Initialise array of character pointers inside a function to be used in main

Time:04-03

How can I initialise array of character pointers inside a function. It should be noted that length comes dynamically from other calculations inside the function. I cannot find length inside main(). For simplicity I have taken rand() to explain scenario.

Is there any way where I can initialise array of character pointers with certain length without passing length from main() to setArgs() ?

With below code I get errors:

temp.c:8:6: error: invalid use of array with unspecified bounds 8 | args[length];

#include<stdio.h>
#include<stdlib.h>

void setArgs(char* (*args)[])
{
    int length = (rand() % 5)   2;

    args[length];
    args[0]="hello\0";
    args[1]="jack\0";
}
int main()
{
    char* myArgs[]={NULL};
        
    setArgs(&myArgs);

    for(int i=0;i<2;i  )
    {
        printf("%s", myArgs[i]);
    }

    return 0;
}

CodePudding user response:

You have two options. Allocate the memory dynamically or first generate the length:

1.

#include<stdio.h>
#include<stdlib.h>

void setArgs(char *** args)
{
    int length = (rand() % 5)   2;
    *args = malloc(sizeof(char *)*length);

    (*args)[0]="hello\0";
    (*args)[1]="jack\0";
}
int main()
{
    char ** myArgs = NULL;       
    setArgs(&myArgs);

    for(int i=0;i<2;i  )
    {
        printf("%s", myArgs[i]);
    }
    free(myArgs);
    return 0;
}

or 2.


#include<stdio.h>
#include<stdlib.h>

void setArgs(char ** args)
{
    args[0]="hello\0";
    args[1]="jack\0";
}
int main()
{
    int length = (rand() % 5)   2;
    char* myArgs[length];
        
    setArgs(myArgs);

    for(int i=0;i<2;i  )
    {
        printf("%s", myArgs[i]);
    }
    return 0;
}

args[length]; doesnt change the length but just does an array-access at the index length

CodePudding user response:

Here is a way to do this:

#include<stdio.h>
#include<stdlib.h>

 char **setArgs()
 {
    int length = (rand() % 5)   2;

    char **args;

    args = malloc(length*(sizeof(char*)));

    args[0]="hello\0";
    args[1]="jack\0";

    return args;
}

int main()
{
    char** myArgs;
    
    myArgs = setArgs();

    for(int i=0;i<2;i  )
    {
        printf("%s", myArgs[i]);
    }

    return 0;
}
  • Related