Noo*_*der 1 c malloc free realloc calloc
#include <stdio.h>\n#include <stdlib.h>\n\nint main()\n{\n int *ptr;\n int n;\n\n printf("Enter the no of elements you want in an array1:");\n scanf("%d",&n);\n printf("The no of elements in array 1 would be %d",n);\n\n ptr=(int*)malloc(n*sizeof(int));\n if(ptr==NULL){\n printf("Memory not alloted ");\n }\n else{\n printf("Memory successfully alloted using malloc");\n }\n\n printf("The elements of array 1 are:");\n for(int i=0;i<n;i++){\n ptr[i]=2*i;\n printf("%d",ptr[i]);\n }\n free(ptr);\n printf("Memory has been successfully freed\\n");\n\n int *ptr1,n1;\n printf("Enter the no of elements you want in an array2:\\n");\n scanf("%d",&n1);\n printf("The no of elements in array 2 would be %d",n1);\n\n ptr1=(int*)calloc(n1,sizeof(int));\n if(ptr1==NULL){\n printf("Memory not alloted \\n");\n }\n else{\n printf("Memory successfully alloted using calloc\\n");\n }\n\n printf("The elements of array 2 are:");\n for(int j=0;j<n1;j++){\n ptr1[j]=j+2;\n printf("%d",ptr1[j]);\n }\n\n ptr1=realloc(ptr1,2*n1*sizeof(int));\n printf("Memory successfully reallocated using realloc");\n printf("The array after reallocation is:");\n \n for(int k=0;k<2*n1;k++){\n ptr1[k]=k+2;\n printf("%d",ptr1[k]);\n }\n \n return 0;\n}\nRun Code Online (Sandbox Code Playgroud)\n我通过声明所有内容来编写此代码,但仍然收到编译错误:
\n#include <stdio.h>\n#include <stdlib.h>\n\nint main()\n{\n int *ptr;\n int n;\n\n printf("Enter the no of elements you want in an array1:");\n scanf("%d",&n);\n printf("The no of elements in array 1 would be %d",n);\n\n ptr=(int*)malloc(n*sizeof(int));\n if(ptr==NULL){\n printf("Memory not alloted ");\n }\n else{\n printf("Memory successfully alloted using malloc");\n }\n\n printf("The elements of array 1 are:");\n for(int i=0;i<n;i++){\n ptr[i]=2*i;\n printf("%d",ptr[i]);\n }\n free(ptr);\n printf("Memory has been successfully freed\\n");\n\n int *ptr1,n1;\n printf("Enter the no of elements you want in an array2:\\n");\n scanf("%d",&n1);\n printf("The no of elements in array 2 would be %d",n1);\n\n ptr1=(int*)calloc(n1,sizeof(int));\n if(ptr1==NULL){\n printf("Memory not alloted \\n");\n }\n else{\n printf("Memory successfully alloted using calloc\\n");\n }\n\n printf("The elements of array 2 are:");\n for(int j=0;j<n1;j++){\n ptr1[j]=j+2;\n printf("%d",ptr1[j]);\n }\n\n ptr1=realloc(ptr1,2*n1*sizeof(int));\n printf("Memory successfully reallocated using realloc");\n printf("The array after reallocation is:");\n \n for(int k=0;k<2*n1;k++){\n ptr1[k]=k+2;\n printf("%d",ptr1[k]);\n }\n \n return 0;\n}\nRun Code Online (Sandbox Code Playgroud)\n谁能告诉我错误是什么以及我应该如何纠正它。
\n该realloc函数返回void *您分配给 a 的 a int *。在 C 中,avoid *和任何其他对象指针之间的转换可以在不进行强制转换的情况下执行。但是,您正在编译的文件的名称具有 .cpp 扩展名。大多数编译器都会看到这一点并将其编译为 C++ 程序,并且在 C++ 中从void *到 的转换int *需要强制转换。
由于代码看起来完全是 C 语言并且您已经使用了 C 标记,因此我假设您想要编译 C 程序。既然如此,请将 main.cpp 文件重命名为 main.c,它应该可以正确编译。