I want to decalre on 2d array, but I want to put a vrailbe into the declartaion
#define MAX_SIZE 512
char* FWdir;
int main()
{
getFwDIR(FWdir); //--> put In FWdir path example: /opt/fw1
char arr [][MAX_SIZE] = {
FWdir,"-t","arg"
};
}
try to iterate over arr in ,didnt get the /opt/fw1 , instead I got an adress
I expoected to get
if I will print arr I waill get
/opt/fw1 -t arg... insead I get "someoutput" -t arg
CodePudding user response:
There are two problems here.
The first is you are passing the pointer FWdir
to getFwDIR()
, but FWdir
is NULL, so getFwDIR()
has nowhere to store the path. In its current formulation of getFwDIR(char *)
, that function cannot dynamically allocate memory for the path either.
The second is that you are attempting to write the contents of the string FWdir
directly into the array arr
, but that is not how strings work in C.
On the first point, you have two obvious options:
- Rewrite
getFwDIR()
to accept a pointer to a pointergetFwDIR(char **)
, and dynamically allocate space for the path in that function:
int getFwDIR(char **p_path)
{
...
*p_path = malloc(MAXIMUM_PATH_LENGTH 1);
... // Proceed to get the path
}
...
int main(void)
{
getFwDIR(&FWdir); //--> put In FWdir path example: /opt/fw1
...
}
But, this does leave the issue of freeing the memory later on.
- Make
FWdir
a string with definite length, and pass that togetFwDIR()
:
#define MAX_SIZE 512
char FWdir[MAX_SIZE];
Since you have, in arr
, effectively limited the path length to 511 characters anyway I would go for the second option, which is easier and safer.
On the second point, you also have two clear options:
- Declare the 2d array first, and pass the first element to
getFwDIR()
:
char arr [][MAX_SIZE] =
{
"","-t","arg"
};
getFwDIR(arr[0]); //--> put In FWdir path example: /opt/fw1
In this one, you do not need FWdir
.
- Copy
FWdir
into the array after initialisation:
char FWdir[MAX_SIZE];
getFwDIR(FWdir); //--> put In FWdir path example: /opt/fw1
char arr [][MAX_SIZE] =
{
"","-t","arg"
};
strncpy(arr[0], FWdir, sizeof(arr[0]));