Search code examples
carraysuser-defined

C program to find the Majority Element of Array using a user defined array size returns unexpected results


I am trying to write a c program that prompts the user to input the size of an array (N) between 1 and 100. Then prompt the user to input array elements to the size of N. Following that I want to display the aforementioned elements to the user, however, in run-time random, or what seems to be random numbers are displayed. I am not sure if this is due to using malloc for user defined array size or what. If you have any insight to what the problem may be I would really appreciate it.

Program:

int main()
{
    int N;
    int dW;
    int *inputArray;
    int counter;

do {
    // Prompts user to input array size up to 100
    printf("\nEnter the value of N up to 100:   \n");
    scanf("%d", &N);

    // Uses pointer "inputArray" to pacify compiler and allocates size of N in memory for array
    inputArray = (int *)malloc(N * sizeof(int));

    // Checks if temp is greater than 1 and less than 100, if yes prompts user to reenter N
    if (N >= 1 & N <= 100)
    {
        
        // Prompts user to input array numbers to the size of N
        for (counter = 0; counter < N; counter++)
        {
            printf("\nEnter the element %d: \n", counter);
            scanf("%d", &inputArray[counter]);
        }

        // displays numbers provided by user
        for (counter = 0; counter < N; counter++);
        {
            printf("%d\n", inputArray[counter]);
        }
        dW = 0;
    }
    else
    {
        printf("\nIllegal Entry, enter a value between 1 and 100\n");
        dW = 1;
    }
    

} while (dW >= 1);
return 0;

}

Output:

Enter the value of N up to 100: 5

Enter the element 0: 1

Enter the element 1: 2

Enter the element 2: 3

Enter the element 3: 4

Enter the element 4: 5

00200000


Solution

  • There are a few issues with your code:

    1. You should move inputArray = (int *)malloc(N * sizeof(int)); into the if-block so that you allocate memory only when you enter the block (and N is guaranteed to be between 1 and 100). Also there's no need to cast malloc() as (int *).

    2. Your second for-loop has a semi-colon at the end: for (counter = 0; counter < N; counter++);. If you leave it there, the for-loop will increment counter until counter == N, and then printf("%d\n", inputArray[counter]); will be called afterwards, but only once and with the wrong index (since counter == N, which would take you out of bounds).

    3. You forget to free(inputArray) after you're done using it. You could do that right after dW = 0;.