【发布时间】:2014-07-22 00:15:35
【问题描述】:
我正在尝试对字符串数组执行插入排序。 该数组被格式化为一个指向 char 数组的指针数组。
数组声明使用:
char *wordlist[ARRAY_LEN];
并使用以下方法传递给插入排序函数:
insertion_sort(wordlist, num_words);
insertion_sort的函数如下。
void insertion_sort(char **a, int n) {
char *key;
int i, p;
for(p=1; p<n; p++){ /*For every item p in the array apart from the first*/
key = *a[p]; /*Set key to the value of p*/
i = p-1;
while(strcmp(*a[i], key) > 0){ /*For every item to the left of p that is larger*/
*a[i+1] = *a[i]; /*than it move it 1 to the right*/
i--;
}
*a[i+1] = key; /*Place key in the vacated leftmost position*/
}
}
我在编译时不断收到与指针相关的错误/警告:
word-sort.c: In function ‘insertion_sort’:
word-sort.c:21:11: warning: assignment makes pointer from integer without a cast
word-sort.c:23:7: warning: passing argument 1 of ‘strlen’ makes pointer from integer without a cast
/usr/include/string.h:399:15: note: expected ‘const char *’ but argument is of type ‘char’
word-sort.c:23:13: warning: cast to pointer from integer of different size
word-sort.c:23:13: warning: cast to pointer from integer of different size
word-sort.c:23:7: warning: passing argument 1 of ‘__builtin_strcmp’ makes pointer from integer without a cast
word-sort.c:23:7: note: expected ‘const char *’ but argument is of type ‘char’
word-sort.c:23:13: warning: cast to pointer from integer of different size
word-sort.c:23:13: warning: cast to pointer from integer of different size
word-sort.c:23:7: warning: passing argument 1 of ‘strlen’ makes pointer from integer without a cast
/usr/include/string.h:399:15: note: expected ‘const char *’ but argument is of type ‘char’
word-sort.c:23:7: warning: passing argument 1 of ‘__builtin_strcmp’ makes pointer from integer without a cast
word-sort.c:23:7: note: expected ‘const char *’ but argument is of type ‘char’
word-sort.c:23:13: warning: cast to pointer from integer of different size
word-sort.c:23:13: warning: cast to pointer from integer of different size
word-sort.c:23:13: warning: cast to pointer from integer of different size
word-sort.c:23:13: warning: cast to pointer from integer of different size
word-sort.c:23:13: warning: cast to pointer from integer of different size
word-sort.c:23:13: warning: cast to pointer from integer of different size
word-sort.c:23:7: warning: passing argument 1 of ‘__builtin_strcmp’ makes pointer from integer without a cast
word-sort.c:23:7: note: expected ‘const char *’ but argument is of type ‘char’
word-sort.c:23:13: warning: cast to pointer from integer of different size
word-sort.c:23:7: warning: passing argument 1 of ‘__builtin_strcmp’ makes pointer from integer without a cast
word-sort.c:23:7: note: expected ‘const char *’ but argument is of type ‘char’
word-sort.c:27:15: warning: assignment makes integer from pointer without a cast
任何关于我哪里出错的想法都会很棒。
【问题讨论】:
-
这种方式不能复制数组 key = *a[p]; .请改用 strcpy()。
-
@Abend
strcpy是错误的方式。 OP 应该只重新分配指针。 -
这段代码有很多问题。纠正编译器错误只是第一步。在尝试完全插入排序之前,您应该从更简单的东西开始,例如可以交换两个字符串的函数。