【问题标题】:Why am I getting error although everything is declared well?为什么我得到错误,虽然一切都被宣布好?
【发布时间】:2021-11-08 17:06:55
【问题描述】:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int *ptr;
    int n;

    printf("Enter the no of elements you want in an array1:");
    scanf("%d",&n);
    printf("The no of elements in array 1 would be %d",n);

    ptr=(int*)malloc(n*sizeof(int));
    if(ptr==NULL){
        printf("Memory not alloted ");
    }
    else{
        printf("Memory successfully alloted using malloc");
    }

    printf("The elements of array 1 are:");
    for(int i=0;i<n;i++){
        ptr[i]=2*i;
        printf("%d",ptr[i]);
    }
    free(ptr);
    printf("Memory has been successfully freed\n");

    int *ptr1,n1;
    printf("Enter the no of elements you want in an array2:\n");
    scanf("%d",&n1);
    printf("The no of elements in array 2  would be %d",n1);

    ptr1=(int*)calloc(n1,sizeof(int));
    if(ptr1==NULL){
        printf("Memory not alloted \n");
    }
    else{
        printf("Memory successfully alloted using calloc\n");
    }

    printf("The elements of array 2 are:");
    for(int j=0;j<n1;j++){
        ptr1[j]=j+2;
        printf("%d",ptr1[j]);
    }

    ptr1=realloc(ptr1,2*n1*sizeof(int));
    printf("Memory successfully reallocated using realloc");
    printf("The array after reallocation is:");
    
    for(int k=0;k<2*n1;k++){
        ptr1[k]=k+2;
        printf("%d",ptr1[k]);
    }
    
    return 0;
}

我通过声明所有内容来编写此代码,但仍然出现编译错误:

main.cpp:50:17: error: invalid conversion from ‘void*’ to ‘int*’ [-fpermissive]
     ptr1=realloc(ptr1,2*n1*sizeof(int));
          ~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~

谁能告诉我错误是什么以及我应该如何纠正它?

【问题讨论】:

  • C++ 不是 C。*.cpp 通常是 C++ 程序的名称。编译器似乎是从您要编译为 C++ 的名称推断出来的。
  • 可能正确的解决方案是mv main.cpp main.c
  • 只有当他们真的想要 C++ 而不是 C,@NevoGoldman。这两种语言在很多方面是不同的语言,将 C 代码编译为 C++ 是一个严重的错误,除非该代码经过精心设计以同时符合两种语言——这很困难,而且很少值得付出努力。 C 或 C++:选择 一个
  • 我认为不进行投射没有任何问题。事实上,您也应该malloccalloc 行中转换为(int )*
  • @NevoGoldman 谢谢..它现在工作了

标签: c malloc free realloc calloc


【解决方案1】:

realloc 函数返回一个void *,您将其分配给int *。在 C 中,void * 和任何其他对象指针之间的转换可以在没有强制转换的情况下执行。但是,您正在编译的文件的名称具有 .cpp 扩展名。大多数编译器会看到这一点并将其编译为 C++ 程序,而在 C++ 中,从 void *int * 的转换需要强制转换。

由于代码看起来完全是 C 并且您使用了 C 标记,我假设您想要编译一个 C 程序。在这种情况下,将 main.cpp 文件重命名为 main.c,它应该可以正常编译。

【讨论】:

    【解决方案2】:

    您使用 C++ 编译器编译 C 程序。您需要:

    1. 如果使用 g++: 添加-xc命令行选项
    2. 如果是 msvc: 添加/Tc 或更好的/TC 命令行选项
    3. 或者只是将.cpp 文件重命名为.c(根据命令行选项,它可能不起作用)

    不要施放或使用任何其他魔法。使用 C++ 编译器编译 C 程序是非常糟糕的,因为它们是不同的语言,而且有很多不同的地方。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-15
      • 1970-01-01
      • 2021-12-17
      • 1970-01-01
      • 2023-02-04
      • 1970-01-01
      • 2021-03-09
      • 1970-01-01
      相关资源
      最近更新 更多