Quantcast
Viewing all articles
Browse latest Browse all 102

Answer by mikyll98 for This code is for printing an array in reverse order in C. But it is not working

Solution

As suggested by Some programmer dude, the error in your code is that you're passing an element of the array (array[n]), instead of the array itself (array), to a function that expects a pointer to integer (void rev_array(int array[], int n)).

To fix your code you just have to change

rev_array(array[n], n);

to

rev_array(array, n);

Note 1

The compiler already tells you why your code can't be compiled:

Compiler stderr<source>: In function 'main':<source>:18:20: warning: passing argument 1 of 'rev_array' makes pointer from integer without a cast [-Wint-conversion]   18 |     rev_array(array[n], n);      |               ~~~~~^~~      |                    |      |                    int<source>:3:20: note: expected 'int *' but argument is of type 'int'    3 | void rev_array(int array[],  int n);      |                ~~~~^~~~~~~

Check this thread for some useful flags to get more warning/errors.


Note 2

In general you shouldn't rely on variable length arrays (such as array[n], where you read n through scanf()), since not every C Standard support them by default. Many compilers do, but the best approach, a part from simple exercises like this, is to use dynamic memory allocation which is made just for this task.


Note 3

Always check scanf() and fscanf() return value to prevent undefined behaviour.

From the current C Programming Language Standard - ISO/IEC 9899:2018 (C18):

The fscanf function reads input from the stream pointed to by stream, under control of the string pointed to by format that specifies the admissible input sequences and how they are to be converted for assignment, using subsequent arguments as pointers to the objects to receive the converted input. If there are insufficient arguments for the format, the behavior is undefined. If the format is exhausted while arguments remain, the excess arguments are evaluated (as always) but are otherwise ignored.


Viewing all articles
Browse latest Browse all 102

Trending Articles