[英]Passing array of strings as an input argument in a function
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.我是 C 的新手,我不确定问题的标题是否与我在这里要问的问题相符。 Basically I have written a bit of code to:
基本上我写了一些代码来:
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.现在我想让排序部分成为一个单独的 function 以实现可重用性。 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.有两种方法可以在 C 中分配字符串数组。
char strings [x][y];
. char* strings[x]
. char* strings[x]
。 An item in this pointer array can be accessed through a char**
, unlike the 2D array version.char**
访问此指针数组中的一项。 The advantage of the 2D array version is faster access, but means you are stuck with pre-allocated fixed sizes. 2D 数组版本的优点是访问速度更快,但这意味着您只能使用预先分配的固定大小。 The pointer table version is typically slower but allows individual memory allocation of each string.
指针表版本通常较慢,但允许对每个字符串进行单独的 memory 分配。
It's important to realise that these two forms are not directly compatible with each other.重要的是要认识到这两个 forms 彼此不直接兼容。 If you wish to declare a function taking these as parameters, it would typically be:
如果你想声明一个 function 将这些作为参数,它通常是:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.