C程序适用于我,但在线显示运行时错误(C Program works for me but shows runtime error online)

编程入门 行业动态 更新时间:2024-10-28 19:25:07
C程序适用于我,但在线显示运行时错误(C Program works for me but shows runtime error online)

下面的代码对我来说很好(代码块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.

更多推荐

本文发布于:2023-07-20 12:50:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1199692.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:在线   适用于   错误   程序   Program

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!