Addressing multidimensional arrays in C

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Addressing multidimensional arrays in C



what is the problem? i think there's no logic problem or compile error



but the loop suddenly stopped after looping 16 times...



is this gcc compiler's error? i almost freaked out ...



like there's no compile error that pops up but doesn't work,,,



thanks in advance : ) sorry for the editing question


#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define RIGHT 0
#define DOWN 1
#define LEFT 2
#define UP 3

int main()

int x,y;
scanf("%d %d", &x, &y);

int **arr;
arr = (int**)malloc(sizeof(int*)*x);
for(int i = 0; i < x; i++) arr[i] = (int*)malloc(sizeof(int) * y );

int x_ = 0, y_ = 0;
int MAX_x = x-1;
int MAX_y = y-1;
int MIN_x = 0;
int MIN_y = 0;
int direction = RIGHT;
int num = 0;

while(true)


arr[x_][y_] = num++;

printf("%d", num);
//printf("%d", arr[x_][y_]);

switch ( direction )


case RIGHT:
if( y_ == MAX_y )

direction = DOWN; MIN_x ++; x_++;

else

y_++;

break;

case DOWN:
if( x_ == MAX_x )

direction = LEFT; MAX_y --; y_--;

else

x_++;

break;

case LEFT:
if( y_ == MIN_y )

direction = UP; MAX_x --; x_++;

else

y_--;

break;

case UP:
if( x_ == MIN_x )

direction = RIGHT; MIN_y ++; y_++;

else

x_++;

break;

default : break;



if(num == x * y )
break;



for(int i = 0; i < x; i ++)

for(int j = 0; j < y; j ++ )

printf("%3d", arr[i][j]);

printf("n");






Welcome to Stack Overflow! Please take the tour and visit the help center to get the most out of this site.
– CJ Dennis
Aug 10 at 11:59





I'd recommend using more descriptive variable names, perhaps something like numberOfRows, numberOfColumns, rowIndex, or columnIndex instead of x_, y_, x, y
– jrh
Aug 10 at 12:00



numberOfRows


numberOfColumns


rowIndex


columnIndex


x_


y_


x


y





Read this question and its answers: stackoverflow.com/questions/42094465/…
– Andrew Henle
Aug 10 at 12:00





Just do int arr[x][y]; and avoid all the complication of malloc
– M.M
Aug 10 at 12:55


int arr[x][y];





There is no multidimensional array in the code.
– too honest for this site
Aug 10 at 15:31





1 Answer
1



In your case LEFT you want to decrement x_, not increment it. change your x_++ to x_--.


case LEFT


x_


x_++


x_--



In your case UP you also want to decrement, so change that x_++ to x_--.


case UP


x_++


x_--



I think your confusion here is that moving up requires a decrement, not an increment.






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS