简体   繁体   中英

Passing an Array as Argument to Function in C

I need to pass an array argument to a function from main, however I cannot figure out why does it pass down only the first element of the array and not the whole array as expected. The values in the array are from argv.

Can someone please point out my mistake?

#define MAXSTRING 1000;

int findMatches (const char *filename, char request[]) {

    // iterating over request[] is giving individual characters of the first word, not all words. 
    // expected to have a full array of input words.
    
    int len = strlen(request);

    for (int i = 0; i < len; i++) {
        printf("%s \n", request[i]); 
    }
}

int main (int agrc, char *argv[]) {

    char *request[MAXSTRING];
    int index = 0;

    for (int i = 1; i < agrc; i++) {
        request[index] = argv[i];
        index++;
    }

    findMatches("filename.txt", request);

    return 0;
}

char request[] is not the same as char *request[MAXSTRING] . The former declares an array of characters (ie a string), the latter an array of pointers to char, ie an array of strings.

So declare it correctly in your function:

int findMatches (const char *filename, char *request[]) {

Next you will need a way to detect the end of the array of strings contained in request . Either pass a count to findMatches() or arrange for the last string to be NULL. If using a count you can redefine the function to accept a count:

void findMatches (const char *filename, char *request[], int n) {
    for (int i = 0; i < n; i++) {
        printf("%s \n", request[i]);
    }
}

And call it like this:

findMatches("filename.txt", request, agrc-1);

Also, the use of MAXSTRING in char *request[MAXSTRING] seems confused. You seem to want an array of strings, but MAXSTRING seems to be a maximum length of a string. It's unlikely that you will have 1000 arguments to your program.

Passing arrays in C is the same as passing by pointer. You don't get the length, the function only sees it as a char *

You'll want to either pass the size or length in too, or wrap it in a struct and pass the struct in.

For passing arrays as argument in C you should pass as (array[], array_size) as it's treating it as just a pointer. So it will make easier for you to follow if you pass array_size too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM