【问题标题】:Passing argument 1 of 'strcpy' makes pointer from integer without a cast传递 'strcpy' 的参数 1 使指针从整数而不进行强制转换
【发布时间】:2017-03-30 01:56:39
【问题描述】:

一个班有几个学生。 我需要按字母顺序对学生进行排序。 老师排序一个数字,这是一个学生编号。我需要打印学生的姓名。但我收到以下错误: [注意] 预期 'const char * restrict' 但参数是 'char' 类型 [警告] 传递 'strcmp' 的参数 1 使指针从整数而不进行强制转换 'strcmp' 的参数 2 和 'strcpy' 的所有参数都会出现警告。

代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() { 
int N, K, k, i, j;
//students names
scanf("%d", &N);
//vector with students names
char vetor[N];
char aux[N];

//get string e load it on vetor
for(i=0; i<N; i++)
    scanf("%s", vetor[i]);

//alphabetic order
for(i=0; i<N; i++) {
    for(j=0; j<N; j++) {
        //string comparison
        if(strcmp(vetor[i], vetor[j]) < 0) {
        //string copy
        strcpy(aux[i], vetor[i]);
        strcpy(vetor[i], vetor[j]);
        strcpy(vetor[j], aux[i]);
        }
    }
}
//get sorted number 
scanf("%d", &K); 
K=vetor[K];
//print sorted student name
printf("%s", vetor[K]);

return 0;
}

【问题讨论】:

  • aux[i] 和 vetor[i] 是单个字符,而不是 strcpy 和 strcmp 期望的字符串
  • 尝试字符向量[N][50];字符辅助[50];在 if 块中,使用 strcpy(aux, vector[i]); strcpy(向量[j],辅助);并且第一个 for 块可以更改为 for(i=0 i
  • @DavidBowling,在 OP 的代码中,auxvetor 指定 char 数组,如果以 null 结尾,则构成字符串。但正如 bruceg 所说,表达式 aux[i]vetor[i] 指定单个字符。这些不会衰减为指针,并且不能被视为字符串。

标签: c


【解决方案1】:

您正在使用 N 大小的 char 数组,但您尝试使用系统调用将字符串从一个数组复制到另一个数组,而不是单个 char

就您的代码而言,您可以这样做:

if(strcmp(vetor, vetor) < 0) {
    //string copy
    strcpy(aux, vetor);
    strcpy(vetor, vetor);
    strcpy(vetor, aux);
}

注意数组就像一个指针:它指向数组的第一个元素。

【讨论】:

    猜你喜欢
    • 2016-03-05
    • 2011-07-05
    • 1970-01-01
    • 1970-01-01
    • 2019-02-18
    • 2021-08-13
    • 2021-11-01
    • 1970-01-01
    相关资源
    最近更新 更多