-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparams.c
54 lines (53 loc) · 1.41 KB
/
params.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <stdlib.h>
#include "params.h"
/*
* Maps a stack of parameters to a char**
*/
ParamStruct processParamStack(pila* P) {
ParamStruct ps;
tipoelemPila t;
//Auxiliar stack to process the parameters contained in the stack
pila aux;
//Count variable
int i = 0;
//We initialize the auxiliar stack
crearPila(&aux);
//We will be increasing the number of parameters in each iterations
ps.argc = 0;
//We pop all the elements from the stack
while(!esVaciaPila(*P)) {
//And we add each of them to the auxiliar stack
t = tope(*P);
pop(P);
push(&aux, t);
ps.argc++;
}
//We allocate memory for the parameters now that we know its number
ps.argv = (char**)malloc(ps.argc*sizeof(char*));
//We extract the parameters from the auxiliar stack
for(i = 0; i < ps.argc; i++) {
t = tope(aux);
pop(&aux);
ps.argv[i] = t.value.name;
}
//We free the memory associated to both stacks
destruirPila(&aux);
destruirPila(P);
//We return the struct of parameters to be used by a command
return ps;
}
/*
* Frees the memory associated to the parameters passed to a command
*/
void removeParamStruct(ParamStruct ps) {
//Count variable
int i;
//We free the memory associated to every parameter
for(i = 0; i < ps.argc; i++) {
free(ps.argv[i]);
ps.argv[i] = NULL;
}
//And finally, the memory associated to the vector of parameters
free(ps.argv);
ps.argv = NULL;
}