【问题标题】:C - "Invalid Conversion from "int*" to "int"C - “从“int*”到“int”的无效转换
【发布时间】:2019-11-20 06:35:52
【问题描述】:

我是编码新手。我试图制作一个具有多种功能的程序,该程序具有不同的线性搜索和冒泡排序功能。我正在使用带有 TDM-GCC 4.9.2 64 位编译器的 DevC++ IDE。我不知道我在哪里犯了错误。 在第 17 和 19 行,它显示错误“从“int*”到“int”的无效转换。

#include<stdio.h>
void LinearSearch(int,int);
void BubbleSort(int,int);
int main()
{
    int i,a[10],n;
    int size=10;
    for(i=0;i<10;i++)
    {
        printf("Enter a number\n");
        scanf("%d",&a);
    }
    printf("Press the button og=f your choice!\n");
    printf("1. Linear Seach    2. Bubble Sort\n");
    scanf("%d",&n);
    if(n==1)
    LinearSearch(a,size); //Invalid Conversion from "int*" to "int
    else if(n==2)
    BubbleSort(a,size);  //Invalid Conversion from "int*" to "int
    else
    printf("You have pressed the wrong button!\n");
}
void LinearSearch(int a[10],int sizA)
{
    int i,s,f=0;
    printf("Enter the search value\n");
    scanf("%d",&s);
    for(i=0;i<10;i++)
    {
        if(s==a[i])
        {
            f=1;
            printf("The Search Avlue is located at position no. %d in the array",i);
        }
    }
    if(f==0)
    printf("Search Value Not Found");
}
void BubbleSort(int a[10],int sizB)
{
    int i,j,k;
    for(i=0;i<10;i++)
    {
        for(j=0;j<10-i-1;j++)
        {
            if(a[j]>a[j+1])
            k=a[j];
            a[j]=a[j+1];
            a[j+1]=k;
        }
    }
    for(i=0;i<10;i++)
    {
        printf("%d  ",a[i]);
    }
}

【问题讨论】:

  • scanf("%d",&amp;a); --> scanf("%d",&amp;a[i]);
  • &amp;a[i] → a + i ;)
  • @greybeard,是的,这两个表达式是等价的。但是,我更喜欢&amp;a[i],因为它更好地描述了我们想要做的事情:增加数组的索引并指向对应的变量。这与将 X Bytes 添加到 X 是 sizeof(data_type) 的数组的指针相同。我只是觉得不太直观。有点难以记住:)

标签: c algorithm


【解决方案1】:

scanf("%d",&amp;a) 应该是scanf("%d",&amp;a[i])

并更正来自

的函数前向声明
void LinearSearch(int,int);
void BubbleSort(int,int);

到

void LinearSearch(int[],int);
void BubbleSort(int[],int);

【讨论】:

    【解决方案2】:

    您的两个函数的声明与定义不匹配。为了清楚起见,您已经声明:

    void LinearSearch(int,int);  //<---the two arguments are int
    void BubbleSort(int,int);    //<---the two arguments are int
    

    但是,最后,您将函数定义为:

    void LinearSearch(int a[10],int sizA); //<---the first argument is an int*
    void BubbleSort(int a[10],int sizB);   //<---the first argument is an int*
    

    如果您想解决您报告的编译错误,请将您的声明替换为这两行!

    P.S. 另请注意,您可能还需要解决其他一些小问题(使用scanf("%d",&amp;a); 时)。正如其中一条评论所指出的,正确的指令应该是scanf("%d",&amp;a[i]);。

    【讨论】:

      猜你喜欢
      • 2020-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-19
      • 2012-05-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多