下面的代码对我来说很好(代码块10.05)并且没有显示各种测试用例的编译时/运行时错误。 但是我在编程网站上在线提交时显示运行时错误。
#include<stdio.h> #include<stdlib.h> /* Here comes newPos() */ int main() { int t,i,n,k,j; scanf("%d",&t); int* a; for(i=0;i<t;i++) { scanf("%d",&n); free(a); a=(int*) malloc(n); for(j=0;j<n;j++) scanf("%d",&a[j]); scanf("%d",&k); printf("%d\n",newPos(a,n,k)); } return 0; }然后我做了一些更改后将其更改为.cpp文件。 即,而不是免费(一)我使用的声明,删除一个; 而不是a =(int *)malloc(n),我使用了语句,a = new int [n]; 然后它在我的编译器和在线上都成功执行。
The following code worked fine for me (code blocks 10.05) and showed no compile-time/runtime errors for various test cases. But showed runtime error as I submitted it online on a programming website.
#include<stdio.h> #include<stdlib.h> /* Here comes newPos() */ int main() { int t,i,n,k,j; scanf("%d",&t); int* a; for(i=0;i<t;i++) { scanf("%d",&n); free(a); a=(int*) malloc(n); for(j=0;j<n;j++) scanf("%d",&a[j]); scanf("%d",&k); printf("%d\n",newPos(a,n,k)); } return 0; }And then I changed it into a .cpp file after making a few changes. i.e., instead of free(a) I used the statement, delete a; and instead of a=(int*) malloc(n), I used the statement, a=new int[n]; Then it executed successfully both on my compiler and online.
最满意答案
第一个错误:
您没有分配足够的内存来存储n整数值。 所以你应该改变:
a=(int*) malloc(n);至:
a=malloc(n * sizeof(int));我也删除了演员,因为它没用,可以隐藏一个被遗忘的包含。
第二个错误:
在分配内存之前,你不能释放a 。 仅在循环结束时释放内存。
C / C ++混合:
在这个答案的评论中,人们正在谈论是否需要演员,特别是在C ++中。 在C中, 你不应该施放 。
如果你愿意做C ++代码,你应该使用new和delete而不是malloc和free 。 老实说,我不知道在使用malloc时C ++中是否需要malloc ,因为在C ++中,我总是使用new 。 但请不要使用C ++编译器编写C代码。 根据您的需要在C和C ++之间进行选择。
First error:
You are not allocating enough memory to store n integer values. So you should change:
a=(int*) malloc(n);to:
a=malloc(n * sizeof(int));I have also removed the cast since it's useless and could hide a forgotten include.
Second error:
You must not free a before allocating memory. Free the memory only at the end of your loop.
C/C++ mix:
In the comments of this answer, people are talking about the need or not to cast, in particular in C++. In C, you should not cast.
If you are willing to do C++ code, you should use new and delete instead of malloc and free. Honestly, I don't know if a cast is needed in C++ when using malloc, because in C++, I always use new. But please, don't write C code with a C++ compiler. Choose between C and C++ depending on your needs.
更多推荐
发布评论