簡體   English   中英

在C中傳遞參數的名稱的mergesort

[英]mergesort of names passing arguments in C

如何傳遞字符串數組的參數,例如* 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);
    }
    }

編碼

你可以做:

void sortnames(char **names, int low, int high, int num_names, int *sizes)

在這里,您在第一個參數上傳遞名稱數組。 第一個坐標的大小必須為num_names ,因此您不會遇到分段錯誤問題。 然后,您可以將最后一個參數傳遞給具有每個字符串長度的數組。 最后一個參數的大小也必須為num_names ,然后size 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分段錯誤。

定義方法

char *arr_ofptr[];

填充元素的示例在這里填充第一個元素

arr_ofptr[0] = "John Smith";

將此數組作為參數傳遞的方法

func(arr_ofptr,..

傳遞此數組的垂直元素的方法

func(arr_ofptr[nth], ..

你可以這樣做:

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,您可以傳遞數組的fist元素的地址。

我希望有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM