[英]Cannot convert parameter 1 from char to const char for strcmp
我剛開始在c中使用指針。 我想通過在命令提示符下輸入字符串來對字符串進行排序。
當我嘗試實現它時,出現以下錯誤:
'strcmp' : cannot convert parameter 1 from 'char' to 'const char *'
您能否指導我,並告訴我如何使用更少的指針和更多的數組來制作代碼?
char *sort(char *sortIt)
{
char *p =sortIt;
//p = (char*)calloc(sizeof(char));
char temp[3];
int len = strlen(sortIt);
for(int i=0;i<len;i++)
{
for(int j=i+1;j<len;j++)
{
if(strcmp(p[i],p[j])>0)
{
strcpy(temp,p[i]);
strcpy(p[i],p[j]);
strcpy(p[j],temp);
}
}
}
for(int ij=0;ij<len;ij++)
printf("%s", p[ij]);
}
int main(char argc, char **argv)
{
char *p=argv[1];
sort(p);
}
在C中,字符串表示以null結尾的字符串。 因此,大多數C庫函數都利用了這一點。 例如, strcmp
, strcpy
等。
所以,你的代碼是錯誤的調用strcmp(p[i],p[j])
和strcpy(temp,p[i])
因為strcmp
和strcpy
處理strings
不是chars
和p[i]
是一個char。
要比較C中的字符,可以只使用if (p[i] > p[j]) ...
復制一個char,你可以只是char c = p[j];
。
編輯:
改變所有
p[i], p[j]
至
&p[i], &p[j]
因為您需要const char指針。 在原始情況下,您將只看字符。
似乎代碼正在嘗試對字符串中的char
進行排序。 代碼中指出的更正和想法。
char *sort(char *sortIt)
{
// After assignment p & sortIt never change. Only need one of these.
char *p =sortIt;
// casting the return of callloc() and malloc() is frowned upon.
// Note: sizeof(char) is _always_ 1
//p = (char*)calloc(sizeof(char));
char temp[3]; // Only 1 char is needed. Best to declare in inner lock
int len = strlen(sortIt); // Better to use size_t len,i,j,ij;
for(int i=0;i<len;i++)
{
for(int j=i+1;j<len;j++)
{
// Only need to compare p[i] > p[j]
if(strcmp(p[i],p[j])>0)
{
// Only need to swap p[i] p[j]
strcpy(temp,p[i]);
strcpy(p[i],p[j]);
strcpy(p[j],temp);
}
}
}
// Only need to print the string once
for(int ij=0;ij<len;ij++)
printf("%s", p[ij]);
// missing return
}
樣品溶液:
char *sort(char *p) {
size_t len = strlen(p);
for (size_t i = 1; i < len; i++) {
for (size_t j = 0; j < i; j++) {
/// As this code changed the order of indexing, maybe p[i] < p[j]
if (p[i] > p[j]) {
char temp;
temp = p[i];
p[i] = p[j];
p[j] = temp;
}
}
}
printf("%s\n", p); // Recommend adding \n
return p;
}
[編輯]
我發現原始的main()
代碼很麻煩。 以下是建議更改的代碼:
int main(char argc, char **argv)
{
// Good to test if argv[1] is valid.
if (argc <= 1) return 1;
// Although legal for historic reasons, best to
// char *p=argv[1];
const char *p=argv[1];
// Since sort() is going to re-arrange p, either sort() allocates new memory
// or we allocate memory here. Then const char *p is not needed.
size_t size = strlen(argv[1]) + 1;
char *q;
q = malloc(size);
memcpy(q, argv[1], size);
// sort(p);
sort(q);
// Good policy to free allocated memory
free(q);
return 0; // Always good to return a value from main()
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.