GCC Struct Doublepointer array init

user2928056

I'm programming something with c and compile it with gcc on ubuntu. I defined on the Struct a double pointer "mark" for an 2 dimensional Array (for a chessboard ). I have to defined it with a double pointer and I'm not allowed to do it with a matrix or something else. I initialized it with a function. It goes right but for any reasons I can't adress mark[0][0]. If i printed the value out i'm getting a very big and wrong value. I debugged it with gdb and found out that at i=4;k=2 the value of mark[0][0] gets wrong, also I cannot rewrite the value, if i do so I'm getting an memory error. Can someone help me here?

#include <stdio.h>
#include <stdlib.h>

struct t_brett{
    //Boardsize
    int n;  
    //Double Pointer for 2-dimensional Array
        int **mark; 
    //number of jump
    int lsgnr;
    //position of the knight Springers
    int x;
    int y;
}t_brett;


int init_brett(struct t_brett *b, int n, int x, int y){
    b->n=n;
    b->lsgnr=2;
    b->x=x-1; b->y=y-1;
    //first Dimension of Array
    b->mark=malloc(sizeof(int)*n+1); 
    int i,k;    
    for(i=0;i<n;i++){
            //second Dimension of Array 
        b->mark[i]=malloc(sizeof(int)*n+1);
        //Init Values: mit 0
        for(k=0;k<n;k++){ 
                b->mark[i][k]=0;
        }
    }
    b->mark[0][0]=0;
    return 0;
}

Method for print: for lines with +----+----+
void gitter(struct t_brett *b){
    int i;
    printf("+");
    for(i=0;i<b->n;i++){
            printf("---+");
    }
    printf("\n");
}

//Method for print: for lines with +  9+  8+
void gitter_zahl(int j,struct t_brett *b){
    int i;
    printf("+");
    for(i=0;i<b->n;i++){
            printf(" %2d+",b->mark[i][j]);
    }
    printf("\n");
}

void print(struct t_brett *b){
    int i; int j=0;
    //printf("+");
    for(i=0;i<b->n;i++){
            gitter(b);
            gitter_zahl(j, b);
            j++;
    }
    gitter(b);
}

int main(){
    struct t_brett b;
    if (init_brett(&b,5, 5, 1)>0) return EXIT_FAILURE;
    print(&b);
}

My Output:

+---+---+---+---+---+
+ 22216880+  0+  0+  0+  0+
+---+---+---+---+---+
+  0+  0+  0+  0+  0+
+---+---+---+---+---+
+  0+  0+  0+  0+  0+
+---+---+---+---+---+
+  0+  0+  0+  0+  0+
+---+---+---+---+---+
+  0+  0+  0+  0+  0+
+---+---+---+---+---+
JackDVD

In the following line, you are making a mistake

b->mark=malloc(sizeof(int)*n+1);

It should be

b->mark=malloc(sizeof(int*)*n+1); 

Basically you are going to store the address of the int array in the first dimension, which could be different for every architecture. So you should you int*.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related