0

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];
}
0

2 Answers 2

2

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];
    ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

trying now @dasblinkenlight
1

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.

1 Comment

Argh I didnt see the "address of" in front of data! Working now. If I had more time I would explore what you mentioned. @Marcus üller

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.