franklin
franklin

Reputation: 35

Why doesnt my scanf work in the function?

When I take the rows and cols from scanf-s into the main function they work. but in this function they dont work, they dont get used in the for loops. whats the problem?

void function (int rows, int cols, int array[S][S])
{   
 int i, j;
 scanf ("%d", &rows);
 scanf ("%d", &cols);

    for (i = 0; i < rows; i++)
    {
        for (j = 0; j < cols; j++)
        {
            while (array[i][j]<1 || array[i][j]>S)
            scanf ("%d", &array[i][j]);

        }
    }
}

Upvotes: 0

Views: 116

Answers (2)

abelenky
abelenky

Reputation: 64682

I think you are complaining that the changes to parameters rows and cols are not visible in the calling function.

This is because C is a pass-by-value language.

The change would be:

int main(void)
{
    int rows;
    int cols
    int array[5][5];

    caller( &rows, &cols, array);  // Pass by pointer, not value.

    /* Now, rows and cols have been properly set */

    return 0;
}

/* Parameters are received as references, not values */    
void function (int *p_rows, int* p_cols, int array[5][5])
{   
 int i, j;
 scanf ("%d", p_rows);
 scanf ("%d", p_cols);

    for (i = 0; i < *p_rows; i++)
    {
        for (j = 0; j < *p_cols; j++)
        {
            while (array[i][j]<1 || array[i][j]>5)
                scanf ("%d", &array[i][j]);
        }
    }
}

Upvotes: 1

user31264
user31264

Reputation: 6727

The condition of while loop may be wrong since the very beginning. You don't know the initial value of array[i][j]

Upvotes: 0

Related Questions