如何传递字符串数组的参数,例如* p [50]?
void sortnames(char array[],int low,int high){
int mid;
if(low<high){
mid=(low+high)/2;
sortnames(array,low,mid);
sortnames(array,mid+1,high);
mergeSort(array,low,mid,high);
}
}
代码
答案 0 :(得分:0)
你可以这样做:
void sortnames(char **names, int low, int high, int num_names, int *sizes)
在这里,您可以在第一个参数上传递名称数组。第一个坐标的大小必须为num_names
,因此您不会遇到分段错误问题。然后,您可以将最后一个参数传递给每个字符串长度的数组。最后一个参数的大小也必须为num_names
,然后sizes[i]
会产生字符串names[i]
的长度。
编辑:分段错误是每当您访问不允许在C中触摸的内存时都会收到的错误。通常在您访问数组元素超出范围时到达。为了避免这种情况,您必须确保使用适当的malloc
调用为阵列分配足够的空间。所以,例如,为了调用你的sortnames
函数,你应该在一个或多或少像这样的字符串数组之前声明(我说或多或少,因为我不知道你正在执行的上下文):
int num_names // This is the number of names you want to read
// Populate the variable num_names
// ...
char **to_sort = malloc(num_names * sizeof(char *));
int i;
for(i = 0; i < num_names; ++ i)
{
to_sort[i] = malloc(max_name_size); // Here max_name_size is a static value
// with the size of the longest string
// you are willing to accept. This is to
// avoid you some troublesome reallocation
}
// Populate the array with your strings using expressions like
// to_sort[i] = string_value;
//...
int *sizes = malloc(num_names * sizeof(int));
for(i = 0; i < num_names; ++ i)
{
sizes[i] = strlen(to_sort[i]);
}
sortnames(to_sort, 0, num_names, sizes);
请记住以空字符串终止字符串以避免调用strlen
时出现分段错误。
答案 1 :(得分:0)
定义方法
char *arr_ofptr[];
填充其元素的示例。填充第一个元素
arr_ofptr[0] = "John Smith";
将此数组作为参数传递的方法
func(arr_ofptr,..
传递此数组的特定元素的方法
func(arr_ofptr[nth], ..
答案 2 :(得分:-1)
你可以这样做:
void sortnames(char *array,int low,int high)
{
int mid;
if(low<high)
{
mid=(low+high)/2;
sortnames(array,low,mid);
sortnames(array,mid+1,high);
mergeSort(array,low,mid,high);
}
}
使用 char * array 传递数组的第一个元素的地址..
我希望这有帮助..