0

I am trying to print an array with specific dimensions, but it prints out wrong entities when it's run.

//code
#include <stdio.h>

int my_array[2] [4] = {
{1, 2, 3, 4}, {5, 6, 7, 8}
};

void print_array(const int h, const int w, char array[][w]) {
   int nRow = h;
   int nColumn = w;
   for(int i = 0; i < nRow; i++)  {
        printf("--- Row %d --- \n", i);
        for(int j = 0; j < nColumn; j++) {
            printf("Column [%d] = %d \n", j, array[i] [j]);
        }
   }
}

int main(int argc, char **argv)
{
    const int array_width = 4;
    const int array_height = 2;
    print_array(array_height, array_width, my_array);
    return 0;
}

After compiling it prints out the next result:

enter image description here

12
  • 4
    char array[][w] should be int array[][w] Commented Dec 12, 2017 at 7:17
  • 1
    @BarmakShemirani And that should be posted as an answer instead. Commented Dec 12, 2017 at 7:20
  • 3
    Then, it gave you some warning, and you should have corrected your code to get no warnings. Commented Dec 12, 2017 at 7:29
  • 5
    @SpongeBobSquarePants doesn't Microsoft allow copying text from the console? Your output should be included as text, not as a screenshot of text where the text is a relative unreadable 5pt. Commented Dec 12, 2017 at 7:41
  • 1
    @BarmakShemirani "Stretching" that to an answer is no so hard. Copy the line into the edit field below. Use some newlines for formatting. Then make a little text starting with "This line ..." and continuing with "because ...". Mention different sizes of char and int and your guesses what they are. The question is not world class, but it is not off-topic. So you should even be safe from downvotes by people from the "good answers to off-topic questions are bad answers" clan. Commented Dec 12, 2017 at 7:56

1 Answer 1

1

Change char array[][w] to int array[][w] in the function print_array, which expects integer array. The compiler would have issued incompatible type warning, but that's easy to miss! Try to compile the program with zero warnings.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.