Search code examples
carraysfunctionscopepass-by-pointer

C program not entering any for loops?


THIS IS A HOMEWORK ASSIGNMENT

My program seems to not be entering any for loops at all. At one point I had every function in main and was operating on 2 global variables without having to pass by reference or by value and everything was working correctly. Since then I have moved my functions out of main and am passing an array by reference and the length of that array into each function, I am getting printf statements that are outside of loops but nothing executes other than that.

According to GDB my program exits with exit code 046.

The program is simple, it takes a value to set as the length of my array and then prompts the user for integer values to fill that array. I then sort the array, thent I print the array, and finally I call getMax(int *array, int n) to print the largest value to the screen.

An example of output is:

Enter the number of elements to be sorted:
3
Enter 10 integers in any order:
2
1
4
Inside sortArray
Inside sort and print
inside setMAx
The largest value in the array is: 0

I seem to have broke something, I should of never messed with it. Here is my attempt.

Thank you for any assistance, I'll be sitting here trying to find my bug.

#include <stdio.h>

void printArray (int *array, int n);
void sortArray (int *array, int n);
void fillArray (int *array, int n);
void getMax (int *array, int n);

int main(void){

    int array[10],n = 0;

    fillArray  (array, n);
    sortArray  (array, n);
    printArray (array, n);
    getMax     (array, n);

    return 0;
}

void sortArray(int *array,int n){
   printf("Inside sortArray\n");

   int temp, c = 0, c2;
   for(c=0;c<n;c++){
        printf("inside for loop SA\n");
        for(c2=c;c2<n;c2++){ 
            if(array[c]>array[c2]){
            temp=array[c];
            array[c]=array[c2];
            array[c2]=temp;
            }
        }
    }
}

void printArray (int *array, int n){
    int c = 0;
    printf("Inside sort and print\n");
    for(c=0;c<n;c++){
            printf("\t%d",array[c]);
    }
    printf("\n");
}

void fillArray (int *array, int n){
    int c = 0;
    printf("Enter the number of elements to be sorted:\n");
    scanf("%d",&n);
    printf("Enter 10 integers in any order: \n");
    for(c=0;c<n;c++){
        scanf("%d", &array[c]);
    }
}

void getMax (int *array, int n){
    printf("inside setMax\n");
    int temp = 0, i = 0;

    for (i = 0;i<n;i++){
        printf("temp: %d", temp);
        if(array[i]>temp)
        temp=array[i];
    }    
    printf("\nThe largest value in the array is: %d\n", temp);
}

Solution

  • void fillArray (int *array, int n) doesn't update the value of n. You should pass n as a pointer, giving fillArray the following signature: void fillArray (int *array, int *n).

    Then, inside fillArray, you would use *n to modify it's value or n instead of &n.

    Lastly, when calling fillArray, you'll call it with &n.