1

I'm working on my class project and I'm currently stuck at the most basic one. Basically I have to fill the stack of boxes using loops and 3d array. The stack is 4 width, 4 length and 3 height and I have to fill boxes with 100 items each.

void main(){
    int boxShleve[3][4][4];
    int i, j, k;
    for (i=0; i<3; ++i){
        for (j=0; j<4; ++j){
            for (k=0; k<4; ++k){
                boxShleve[3][4][4] = 100;
            }
        }
    }
    printf("%d", boxShleve[3][4][4]);
}

This is the broken piece of my work... How do I make each array has 100 element in it?

3
  • 2
    You never use the index variables i, j or k as indexes in the array. Instead you have the size as index, and as you (should) know arrays are indexed from zero to size minus one, so those indexes are all out of bounds. Commented Apr 6, 2014 at 15:51
  • consider what happens when you fill an array int box[4]; initialize them properly and then printf("%d", box[4]); when you have 0 indexing. Commented Apr 6, 2014 at 16:00
  • printf("%d", boxShleve[3][4][4]); --> printf("%d", boxShleve[2][3][3]); Commented Apr 7, 2014 at 0:00

3 Answers 3

3

This is what you meant to do:

int main()
{
    int boxShleve[3][4][4];
    int i, j, k;

    for (i = 0; i < 3; ++i)
        for (j = 0; j < 4; ++j)
            for (k = 0; k < 4; ++k)
                boxShleve[i][j][k] = 100;

    for (i = 0; i < 3; i++)
        for (j = 0; j < 4; j++)
            for (k = 0; k < 4; k++)
                printf("%d ", boxShleve[i][j][k]);

    return 0;
}

The reason you need the nested loops is to use the i, j and k as indexes to access the array. So you have to use them.

Same for printing the values.

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

Comments

0

A faster way to do this if you are using GCC is as follows.

int boxShleve[3][4][4] = {
    {[0 ... 2] = 100 },
    {[0 ... 3] = 100 },
    {[0 ... 3] = 100 } };

Comments

0
#include <stdio.h>

int main(){
    int boxShleve[3][4][4];
    size_t size = sizeof(boxShleve)/sizeof(int);
    int *p = &boxShleve[0][0][0];
    while(size--)
        *p++ = 100;
    printf("%d\n", boxShleve[2][3][3]);//last element,
    return 0;
}

Comments

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.