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:
- Ask for the user input for a string each time and fill up the array of string.
- 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!
There are two ways you can allocate an array of strings in C.
char strings [x][y];
.char* strings[x]
. An item in this pointer array can be accessed through achar**
, 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:
or