简体   繁体   English

c中的分段错误(核心转储)

[英]Segmentation fault (core dumped) in c

I've been writing ac code which takes in an array of integers and adds 1 every value in the array however i ger a segmentation fault .. Iam new to C and do not have any idea what causes this error Here is the code: 我一直在编写一个ac代码,它接受一个整数数组并在数组中添加1个但是我有一个分段错误。我刚接触C并且不知道是什么导致这个错误这是代码:

#include <stdio.h>
void add1(int a[]){
    int i;
    for(i=0;i<sizeof(a);i++){
a[i]=a[i]+1;
    }
}


void main(){
    int arr[10]={1,2,3,4,5,76,7,5,3};
    add1(arr);
int i;
for(i=0;i<sizeof(arr);i++){
arr[i]=arr[i]+1;
printf("%d ",arr[i]);
}


}

I can identify three issues in your program and would list them in progression of severity 我可以在您的程序中识别出三个问题,并将其列入严重程度

  1. (Code Error) Array size is not the same as size of an array object (代码错误)数组大小与数组对象的大小不同

     for(i=0;i<sizeof(arr);i++) 

    Your assumption that the sizeof would return you the array size (no of elements) is wrong. 你假设sizeof会返回数组大小(没有元素)是错误的。 sizeof is used to calculate the size of the datatype, which in this case is an array of integers of size 10. sizeof用于计算数据类型的大小,在本例中是一个大小为10的整数数组。

    You should instead have done 你应该做的

     for(i=0;i<sizeof(arr)/sizeof(arr[0]);i++) 

    which means, size of the array object as a reciprocal of sizeof a single array element. 这意味着,数组对象的大小是单个数组元素的大小的倒数。

  2. (Functional Error) Array degenerates to a pointer when you pass it to a function. (功能错误)将数组传递给函数时,数组会退化为指针。

     void add1(int a[]){ int i; for(i=0;i<sizeof(a);i++){ 

    So, the sizeof would instead return the size of an integer pointer rather than the size of the array. 因此, sizeof将返回整数指针的大小而不是数组的大小。 You should instead pass the array size as an additional parameter 您应该将数组大小作为附加参数传递

     void add1(int a[], size_t sz){ int i; for(i=0;i < sz;i++){ 
  3. (Style) Initialization of an array does not require an explicit array size (样式)数组的初始化不需要显式数组大小

     int arr[10]={1,2,3,4,5,76,7,5,3}; 

    should be 应该

     int arr[]={1,2,3,4,5,76,7,5,3}; 

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

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