-1
#include<stdio.h> 
#define SIZE 15

int * Check_Wrong_Question(char User_Answer[SIZE],char MCQ_Answer[SIZE])
{
    int i, j;

    i = 0;
    j = 0;

    static int Wrong_Question[SIZE];

    for(i = 0; i < SIZE; i++)
    {
        if(User_Answer[i] != MCQ_Answer[i])
        {
            Wrong_Question[j] = i+1;
            j++;
        }
    }

    return Wrong_Question;
}

int main()
{
    char MCQ_Answer[SIZE] = {'d','b','a','c','b','c','a','b','d','c','d','b','d','a','a'};
    char User_Answer[SIZE];
    int i,j;
    int *Wrong_Question;

    i = 0;
    j = 0;

    for(i = 0; i < SIZE; i++)
    {
        printf("Q%d)", i+1);
        scanf("%c", &User_Answer[i]);
    }

    Wrong_Question = Check_Wrong_Question(User_Answer,MCQ_Answer)

    while(Wrong_Question[j] != 0)
    {
        printf("%d\n", Wrong_Question[j], j++);
    }

    return 0;
}

The codes are in C program.The error part is if the user enter all answer as 'a', it should print out 1,2,4,5,6,8,9,10,11,12,13. But it shows 2,4,5,6,7,8,9,10,11,12,13,0. It print from 2nd element of array although i declared j=0 to print from 1st element. And it shouldn't have print 0 since my condition is != 0. Did the return of array from its function alter the data? I tried to print array in the function and it works fine. Also,I'm new to C program.

Claudio Cortese
  • 1,372
  • 2
  • 10
  • 21
Jusle
  • 13
  • 5

1 Answers1

1

The problem is with the while-loop at the end of your program:

while(Wrong_Question[j] != 0)
{
    printf("%d\n",Wrong_Question[j],j++);
}

You are using both j and j++ in the same statement. The C standard makes no guarantee in which order these are executed in this case. It is better to rewrite this as a for-loop, like so:

for(j = 0; Wrong_Question[j] != 0; j++)
{
    printf("%d\n", Wrong_Question[j]);
}
G. Sliepen
  • 7,637
  • 1
  • 15
  • 31
  • It works! Could you explain more on 'The C standard makes no guarantee in which order these are executed in this case' ? – Jusle Feb 01 '17 at 14:22
  • @Jusle: the order in which function parameters for a single function call are evaluated is not defined in the C standard. The compiler can choose if it evaluates `Wrong_Question[j]` first or `j++` first. It so happens that in your case, it does `j++` first, giving you the wrong result for `Wrong_Question[j]`. See also [this question](http://stackoverflow.com/questions/376278/parameter-evaluation-order-before-a-function-calling-in-c). – G. Sliepen Feb 01 '17 at 16:44