Home > Net >  Passing array of strings as an input argument in a function
Passing array of strings as an input argument in a function

Time:03-30

I'm new to C and I'm not to sure if the title of the question is correct with what I'm about to ask here. Basically I have written a bit of code to:

  1. Ask for the user input for a string each time and fill up the array of string.
  2. Sort the array of string alphetically.
    char ch_arr[nV][MAX_WORD_LENGTH];
    for (int i = 0; i < nV; i  ) {
        printf("Enter a word: ");
        scanf(FORMAT_STRING, ch_arr[i]);
    }

    //sort array of string alphabetically
    char temp[MAX_WORD_LENGTH];
    for (int i = 0; i < nV; i  ) {
        for (int j = i 1; j < nV; j  ) {
            if (strcmp(ch_arr[i], ch_arr[j]) > 0) {
                for (int c = 0; c < MAX_WORD_LENGTH; c  ) {
                    temp[c] = ch_arr[i][c]; 
                    ch_arr[i][c] = ch_arr[j][c]; 
                    ch_arr[j][c] = temp[c]; 
                }
            }
        }
    }

Now I want to make the sorting part to become a seperate function for reuseability. The example I've read are all using double pointer to a character, but I'm not too sure how to apply it in here?

Thank you very much for reading. And any help would be greatly appreciated!

CodePudding user response:

There are two ways you can allocate an array of strings in C.

  • Either as a true 2D array with fixed string lengths - this is what you have currently. char strings [x][y];.
  • Or as an array of pointers to strings. char* strings[x]. An item in this pointer array can be accessed through a char**, unlike the 2D array version.

The advantage of the 2D array version is faster access, but means you are stuck with pre-allocated fixed sizes. The pointer table version is typically slower but allows individual memory allocation of each string.

It's important to realise that these two forms are not directly compatible with each other. If you wish to declare a function taking these as parameters, it would typically be:

void func (size_t x, size_t y, char strings[x][y]); // accepts 2D array
void func (size_t x, size_t y, char (*strings)[y]); // equivalent, accepts 2D array

or

void func (size_t x, char* strings[x]); // accepts pointer array
void func (size_t x, char** strings);   // equivalent - accepts pointer array
  • Related