Question

I've been writing a C code which takes in an array of integers and adds 1 to every value in the array. However, I get a segmentation fault.

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]);
}


}
Was it helpful?

Solution

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};
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top