简体   繁体   中英

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:

#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 is used to calculate the size of the datatype, which in this case is an array of integers of size 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. 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}; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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