1

I'm learning about multidimensional array in C programming. But the printf function is not working. Here is my code:

#include <stdio.h>
int main (void)
{
  int array[2][3][4]; 
  for (int i = 0; i < 3; i++)
  {
    for (int j = 0; j < 4; j++)
     {
        for (int k = 0; k < 5; k++)
        {
            array[i][j][k] = k;
            printf("array[%d][%d][%d] = %d\n", i, j, k, array[i][j][k]);
        };
    };

};
printf("Loop is finished!");
return 0;
}
1
  • 3
    You're overrunning your array indices. int[2] means you have 2 elements, i.e. you can access indices 0 and 1, but you're accessing 2. Commented Aug 12, 2014 at 3:34

2 Answers 2

4

You are going to loop out of bounds.

Take the first dimension, 2, your loop is < 3.... so its going to use indexes 0 1 2. only 0 and 1 are valid. change your loops to i < 2, j < 3 and k < 4 respectively.

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

6 Comments

There are only two hard things in computer science: cache invalidation, naming things, and off by one errors.
Thank you solved my problem :) but why I can't use 3 elements for [2], for example {1,2,3} because of null terminator?
does it works properly? it having lots of syntax errors see my answer
@Amession you only allocated space for 2 things, if you want 3 things, make the size 3.
it is because the array is declared as ` int array[2][3][4];` you can make the change as said in this answer or correct the errors and see my answer which will also give result change is that` int array[3][4][5];`
|
0

This program will not give result since it having lots of Syntax errors. you need not to be give ;- semicolon after for loop

syntax for For Loop is:

FOR( initialization expression;condition expression;update expression)
{
\\Loop content comes here
}

And also C will not permit Instant Declaration, variables should be declare @ the declaration section.

Your Program can be improved by applying these changes, then it gives output. the code snippet will be like the following:

#include <stdio.h>
int main ()
{
  int array[3][4][5]; 
  int i,j,k;
  for ( i = 0; i < 3; i++)
   {
     for ( j = 0; j < 4; j++)
      {
        for (k = 0; k < 5; k++)
        {
            array[i][j][k] = k;
            printf("array[%d][%d][%d] = %d\n", i, j, k, array[i][j][k]);
        }
      }
  }
  printf("Loop is finished!");
  return 0;
} 

1 Comment

yes the semicolon after bracket was wrong :) but your program doesn't work, the last printf won't show the output

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.