cba1067950 cba1067950 - 4 years ago 94
C Question

Parsing C string and multiple pointer c string

I'm trying to make a parser. I have a version working with just pointers but I want to know how to convert it from pointers (char *p) to c strings (char p[]) to get more familiar with how they work.

I have a function...

int makearg(char s[], char**args[])
{
char *arg1
char arg2[50];

//I'm aware these don't assign the args pointer value to arg2.
arg2[0] = args[0];

//And I'm aware this does.
arg1 = (*args)[0]);
}


My question is what is the equivalent. Or maybe a brief explanation on what's going on. Other solutions just give working code without really saying how it works.

I don't think this is related by my mem allocation is using the pointer and []. And that works fine. Little unsure how that works also if anyone has time.

(*args)[i] = (char*) malloc(sizeof(char) * tokenLen);

Answer Source

The first statement:

arg2[0] = args[0];

arg2[0] is of type char and args[0] is of type char**. This assignment wont work because they are of different types.

However, something like this would work:

arg2[0] = (**args)[0]; /* or even (*args)[0][0] */

because you are giving arg2[0] a char, which is correct because they are matching types. **args is a pointer to a pointer to the first element of args, which is char*, and to reach a char, you need to index [0]. Their are multiple ways you could do this. Assigning arg2[0] to args[0][0][0] or even ***args is valid, even though these assignments would look obscure.

The second statement:

arg1 = (*args)[0];

will work because you are giving arg1, a char* pointer.*args is a pointer to first element of of args, which is char**, and index[0] locates to a char* pointer. This stores the address of (*args)[0]; within arg1. This could even be written in a much less popular way &(*(*args)[0]), although this is harder to read and not necessary.

Additionally, Your memory allocation is fine. (*args)[i] is a pointer to the first element of args, which is char**, and [i] would reference a char* pointer. You would need to allocate for char** before hand, as this is also an uninitialized pointer to pointer.

You can also shorten:

(*args)[i] = (char*) malloc(sizeof(char) * tokenLen);

to:

(*args)[i] = malloc(tokenLen);

As you don't need to cast return of malloc(), and sizeof(char) is always 1. '

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download