ojhawkins
ojhawkins

Reputation: 3278

assign pointer from argv in function

I am trying to assign a pointer correctly from the programs **argv. When I assign data in the main function it works fine, but when I attempt to place that logic into a separate function it does not.

What am I doing wrong here?

void parse_args(char *argv[ ], unsigned char *data, *data_len,  *nprocs){

    data = (unsigned char *)argv[1];
    *data_len = strlen(argv[1]);
    *nprocs = atoi(argv[2]);
}

int main(int argc, char **argv) {
    unsigned char *data;
    int  data_len;
    int   nprocs; 

    // this doesnt work (for data)
    parse_args(argv, data, &data_len, &nprocs)

    // this works (for data)
    data = (unsigned char *)argv[1];
}

Upvotes: 0

Views: 519

Answers (2)

Marcus Müller
Marcus Müller

Reputation: 36352

your function needs to be passed a char * [] (which is equivalent to a char** in an argument specification). You shouldn't specify the type when calling a function, that should have given you a compiler error (char * is not to be used here!)

// this doesnt work (for data)
parse_args(char *argv, data, &data_len)

must be replaced by

parse_args(argv, data, &data_len)

So, next, you pass a pointer data , but you pass that pointer by value, i.e. your parse_args gets a nice copy of that pointer (which, technically, is just an address stored in a variable), and then you modify that copy. You might want to pass it like data_len:

void parse_args(char *argv[ ], unsigned char **data, *data_len,  *nprocs){
..
parse_args(argv, &data, &data_len, &nprocs)

All in all, this doesn't seem to be a great attempt at argument parsing. There's lots of libraries out there to do that for you, and if you want to stay old-school, I'd recommend using gengetopt, which generates all the parsing code you need and has nice documentation.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

This line

data = (unsigned char *)argv[1];

modifies a local copy of main's local data, because all parameters, including pointers, are passed by value. If you would like to modify data inside main, pass it by pointer (i.e. you need a pointer to pointer now):

void parse_args(char *argv[ ], unsigned char **data_ptr, int *nprocs) {
    ...
    *(data_ptr) = (unsigned char *)argv[1];
    ...
}

Upvotes: 2

Related Questions