Search code examples
arrayscincrementfunction-definition

How to edit an array in another function than the main function in c programming?


I'd like to increase each element in the array by one in another function than the main function. Then, I'd like to call this function and print in the main function.

#include <stdio.h>

int function(int array2[5]) {

    int i;
    while(i<4) {
        array2[i]=array2[i]+1;
        i++;
    }

    return array2[5];
}

int main() {
int array[5]={1,2,3,4,5};
int answer;

answer[5]=function(array[5]);

int j;
while(j<4) {
    printf("%d \n",answer[j]);
    j++;
}

return 0;
}

Solution

  • There you go. I suppose this is what you want:

    #include <stdio.h>
    
    // Since the array named parameters are scoped only within its function,
    // they are apart from your array in the main.
    void function(int array[], int len) {
        
        int i = 0;
        while(i<len) {
            array[i]=array[i]+1;
            i++;
        }
    }
    
    // Or alternatively you can process the array using a pointer
    void functionWithPointer(int *array, int len) {
        
        int i = 0;
        while(i<len) {
            *(array+i) = *(array+i)+1;
            i++;
        }
    }
    
    int main() {
        int array[]={1,2,3,4,5};
    //  int answer; // Not necessary
        int length = sizeof(array) / sizeof(int); // !!!ATTENTION
        
        function(array, length);
        
        // The array values updated by 1
        printf("Array values after 1st update\n");
        for(int k=0; k<length; k++) {
            printf("%d \n",array[k]);
        }
        
        functionWithPointer(array, length);
        
        // The array values updated by 1 again
        printf("Array values after 2nd update\n");
        int j;
        while(j<length) {
            printf("%d \n",array[j]);
            j++;
        }
        
        return 0;
    }
    

    Here is the output:

    Array values after 1st update
    2 
    3 
    4 
    5 
    6 
    Array values after 2nd update
    3 
    4 
    5 
    6 
    7