【发布时间】: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++:选择 一个。
-
我认为不进行投射没有任何问题。事实上,您也应该不在
malloc和calloc行中转换为(int )*。 -
@NevoGoldman 谢谢..它现在工作了
标签: c malloc free realloc calloc