简体   繁体   English

分段错误错误:同时减去两个数组

[英]Segmentation Fault error: while subtracting two arrays

I cannot subtract two arrays which are declared using malloc.what is the problem? 我不能减去使用malloc声明的两个数组。这是什么问题?

#include<stdio.h>
#include<conio.h>
void main()
{
float *a,*b,*c;
int i;
a=(float*)malloc(8*sizeof(float));
b=(float*)malloc(8*sizeof(float));
c=(float*)malloc(8*sizeof(float));
a[1]=8.0;a[2]=9.0;a[3]=1.0;a[4]=2.0;a[5]=0.0;a[6]=8.0;a[7]=18.0;a[8]=2.0;
b[1]=10.0;b[2]=1.0;b[3]=13.0;b[4]=0.0;b[5]=100.0;b[6]=1.0;b[7]=20.0;b[8]=0.0;
for(i=1;i<=8;i++)
{
c[i]=a[i]-b[i];
printf("%d",c[i];// IAM GETTING ERROR HERE
}
getch();
}

a = (float*)malloc(8*sizeof(float));

This will allocate 8 continuous chunks , each of size equal to size of float and returns pointer to the first chunk and the value at each chunk can be accessed as 这将分配8个连续的块,每个块的大小等于float的大小,并返回指向第一个块的指针,并且每个块的值可以通过以下方式访问:

a[0], a[1] ,..., a[7] or *(a), *(a+1), ..., *(a+7) a[0], a[1] ,..., a[7]*(a), *(a+1), ..., *(a+7)

In your code, I can see a[8], b[8], c[8], modify your code to go from 0 to 7 rather than from 1 to 8 在您的代码中,我可以看到a [8],b [8],c [8],将您的代码修改为从0到7,而不是从1到8

Gautam seems to have already answered your question in the comment, and I'd like to make it clearer. Gautam似乎已经在评论中回答了您的问题,我想更清楚一点。

Segmentation Fault is almost always due to inappropriate memory usage, and in your case the culprit is c[8]. 分段错误几乎总是由于不适当的内存使用造成的,而您的罪魁祸首是c [8]。 Remember that in languages like C, you count from 0, that is, if the length of an array is 8, its index should be 0, 1, ... 7. In fact, the indices are more like offsets; 请记住,在像C这样的语言中,您从0开始计数,也就是说,如果数组的长度为8,则其索引应为0、1,...7。实际上,索引更像是偏移量; the first element doesn't need any offset and hence with index 0, the second element need to have one offset (the size of an array element) added, the third needs two, the fourth needs three, et cetera. 第一个元素不需要任何偏移,因此索引为0,第二个元素需要添加一个偏移(数组元素的大小),第三个元素需要两个,第四个需要三个,等等。

For malloc(): every chunk of memory allocated should be freed eventually to avoid memory leak. 对于malloc():最终应释放分配的每个内存块,以避免内存泄漏。 In your situation, why not just declare three arrays with length eight? 在您的情况下,为什么不只声明长度为8的三个数组? That'll spare you from worrying about these. 这将使您不必担心这些。

Format String: "%d" is used to print out decimals, while "%f" is for floats. 格式字符串:“%d”用于打印小数,而“%f”用于浮点数。 If you wanna see floating point numbers on the screen "%f" is what you should go for. 如果您想在屏幕上看到浮点数,“%f”应该是您想要的。 (also the right parenthesis is missing in your printf(). I assume it's just a typo) (您的printf()中也缺少正确的括号。我认为这只是一个错字)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM