I was researching but could not find a way. I am passing 2 char array pointers
to a function and fill those 2 arrays with values. Is there a way to get the size of the filled arrays?
I tried size_t size = sizeof(*arguments)/sizeof(arguments[0])
already but that gave me 1 as a result, I know why its giving me 1 as result by researching but I just couldn't find a way to get the proper array length(the value how much elements are in the array). If that is not possible how can I work around this ? I need to know this because, I wanna give the last value of any array a NUL
L for my exec
functions. My programs works as follows:
An user inputs 2 program names which are executed. But the 2 programs are separated by a ";"
. So I have 2 arrays which can vary in size , which depends on the input in the terminal.
void getArguments(char * [],char * [], int ,char * []);
int main(int argc, char * argv[]){
pid_t pid,pid2;
char * arguments2[argc/2+1];
char * arguments[argc/2+1];
getArguments(arguments, arguments2,argc,argv);
if((pid=fork())==-1){
printf("Error");
}
else if(pid == 0){
execvp(arguments[0],arguments);
}
else{
if((pid2 = fork())== -1){
printf("Error" );
}
else if(pid2 == 0 ){
execvp(arguments2[0],arguments2);
}
else{
int status;
wait(&status);
exit(0);
}
}
return 0;
}
void getArguments(char * arguments[], char * arguments2[],int argc, char * argv[]){
int i=0;
while(strcmp(argv[i+1],";")!=0){
arguments[i] = argv[i+1];
i++;
}
arguments[argc/2-1]= NULL;
int j = i+2;
int k = 0;
for( ;j<=argc; j++){
arguments2[k] = argv[j];
k++;
}
arguments2[argc/2-1]=NULL;
}
No, you can't get the size of an array if you only have a pointer. You must pass the size as a separate argument to your function.
EDIT: I now understand you need to return from your function the number elements used in the array. You can either add two integer pointer variables that receive the size, or you could set the first unused element to NULL so the caller knows when it is at the end of the filled portion.
For example:
char * arguments2[argc]; // as you don't know the result, do not divide by 2: it may be too small!
char * arguments[argc];
int size1=0, size2=0;
getArguments(arguments, &size1, arguments2, &size2, argc, argv);
And:
void getArguments(char *arguments[], int *size1, char *arguments2[], int *size2, int argc, char *argv[])
{
// ...
*size1= i;
//...
*size2= j;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments