C_Intermediate_Learner
C_Intermediate_Learner

Reputation: 1820

Bug in multi-dimensional array program in C

I've made a C program that involves multi-dimensional arrays (it prints a multi-dimensional array of characters) to review a little, but I came across a bug.

My expected output of the program is:

.
.
.
A
.
.
.
.
.

However the output I get is:

.
.
A     //Not meant to be 'A' but rather a '.'
A
.
.
.
.
.    

I am wondering how I get that extra 'A' in position [0][2], and how I can fix this problem.

Here is my code:

#include <stdio.h>

void initArray(char shape[][2]);

main()
{
      char shape[2][2];
      int i, j;

      initArray(shape);
      shape[1][0] = 'A';
      printf("%c\n%c\n%c\n", shape[0][0], shape[0][1], shape[0][2]);  
      printf("%c\n%c\n%c\n", shape[1][0], shape[1][1], shape[1][2]);
      printf("%c\n%c\n%c\n", shape[2][0], shape[2][1], shape[2][2]);

      getchar();
}

void initArray(char shape[][2])
{
      int  i, j;

      for(i = 0; i < 3; i ++)
      {
            for(j = 0; j < 3; j++)
            {
                  shape[i][j] = '.';                  
            }
      }
}

Thank you very much =D

Upvotes: 0

Views: 130

Answers (2)

A possible way would be to avoid multi-dimensional arrays, and use plain arrays. Then instead of char shape[2][2]; you would declare

 char shape[4];

and code shape[2*i+j] instead of shape[i][j]. (BTW the compiler transforms the later into the former).

Use a debugger (like gdb) to see if i and j have meaningful values. And add assert(i>=0 && i<2) at appropriate places.

Remember that an array declared char arr[4]; (like my shape above) accepts only index from 0 to 3 (i.e. 4-1) i.e. use arr[0], ... arr[3] or arr[i] with the integral i between 0 and 3. Accessing arr[4] (or arr[17] or arr[i+1] when i is 3) is an undefined behavior (anything could happen per the C standard, including the collapse of the universe, which would be standard compliant). This particular error is quite common and called a buffer overflow. It is used in malware.

Upvotes: 1

P0W
P0W

Reputation: 47794

Because you need to loop till < 2 as shape is declared as shape[2][2]

 for(i = 0; i < 2;i++)
   for(j = 0; j < 2; j++)

This will iterate over the shape on row & columns 0-1 both inclusive

Upvotes: 3

Related Questions