Search code examples
creturn

C programming ... Why "return" statement give only one value in this code?


I'm newbie for coding C. I'm trying to write a program which is adding a value at the first position the array. As shown below, append function must return more than one value.

When I use printf("%d ", array[c]) statement in this function, there is no problem and I get the values what I want.

However, when I use return s; statement in this function, it gives only one value, although it must give same values with printf("%d ", array[c]) statement.

When I run this code with printf("%d ", array[c]), the output is:

25, 5, 8, 555, 99

When I run this code with return s, the output is;

25

Why there is a different between two statements? I don’t need to print the values on screen. I need to use return statement. Please help me for this…

#include <stdio.h>

int append(int array[]){

          int  position, c, s, len=4, value=25; 

          position=1;

          for (c = len - 1; c >= position-1; c--){
              array[c+1] = array[c];
              }
          array[position-1] = value;
          for (c = 0; c <= len; c++){

                //return array[c]; // <-- why this give only one value???   
                printf("%d ", array[c]);    //<--  this print the all value !!! 
              }          
}

int main(){

    int kar[]= {5, 8, 555, 99};

    printf("%d", append(kar));

    return 0;
}

Solution

  • You're passing array to the function, which is actually passing a pointer to the first element of the array. This means that changes to the array in the function also will appear in the calling function since it's the same array.

    You don't need to return anything. Just print the contents of the array in main.

    Also, an array of size 4 has indexes from 0 to 3. Right now you're writing past the end of the array. You need to change your function to prevent that. You can't just write past the end of the array to make it bigger. The size is fixed.

    void append(int array[]){
          int  position, c, s, len=4, value=25; 
          position=1;
    
          for (c = len - 2; c >= position-1; c--){
              array[c+1] = array[c];
          }
          array[position-1] = value;
    }
    
    int main() {
        int kar[]= {5, 8, 555, 99};
    
        append(kar);
    
        int c;
        for (c = 0; c < 4; c++){
            printf("%d ", kar[c]);
        }       
        return 0;
    }