farid99
farid99

Reputation: 712

Two Dimensional Array of Structs in C - how to declare and use

I've been trying to get a very simple idea to work in C but I can't even get the syntax down.
This program would take in some inputs from the command line and use them to decide what size to make a 2 dimensional array of structs.

Then, in a for-loop type situation, I'd like to be able to change a specific unsigned char based on user input. So first I build a 2D array of structs, each struct containing an array of unsigned chars as well as a name, and then I am able to write to these.

The command line arguments are three strings. First one is number of rows, second one is number of columns, third one is size of unsigned char array within each struct.

#include<stdio.h>
#include<stdbool.h>
#include<math.h>
#include<stdlib.h>
#include<string.h>
    typedef struct {
    unsigned char* Data;
    char* name;
    } myStruct;

    myStruct* myArr[][];

    int main(int argc, char *argv[])
    {
       int y = atoi(argv[0]);
       int x = atoi(argv[1]);
       int z = atoi(argv[2]);
       myStruct* myArr[x][y];

      for (int i = 0; i < x; i++)
     {
         for(int j = 0; j < y; j++)
        {
           myArr[i][j]=(myStruct*) malloc(sizeof(myStruct));
           myArr[i][j].Data=(unsigned char*)  malloc(sizeof(unsigned char)*z);  
           myArr[i][j].name = (char*) malloc(sizeof(char)*64);
        }
     }

     //part II - change some entry of myArr based on input from user
     //assume input has been taken in correctly
     int h = 5;//5th row in myArr
     int k = 7; // 7th column in myArr
     int p = 9; //9th unsigned char in myArr[h][k].Data
     unsigned char u = 241;//value to be written
     char* newName = "bob";
     myArr[h][k].Data[p]=u;
     myArr[h][k].name=newName;

     return 0;
    }

This code does not work. In fact, it does not compile. Could someone help me? I am simply trying to understand pointers as a way to transition from java to C. This is the kind of thing I'd be able to do very very easily in Java and I want to be able to do it in C as well. I've heard that a 2 D array has to be declared outside main so it is global in scope, because the stack is limited in size and a 2D array of structs just might fill it. Can someone explain that, too? And how I would declare a 2D array whose size is determined at run time?

I intend to use C and only C for this, too. So please don't provide me with C++ syntax tips. Thanks.

Upvotes: 1

Views: 13491

Answers (1)

Min Fu
Min Fu

Reputation: 809

 myArr[h][k].Data[p]=u;
 myArr[h][k].name=newName;

should be

 myArr[h][k]->Data[p]=u;
 myArr[h][k]->name=newName;

because they are pointers. The same error occurs in your loops.

myStruct* myArr[][];

This line is invalid and meaningless, because you re-define it in the main().

If you want to allocate a dynamical array, you can use:

myStruct **myArr = malloc(x * y * sizeof(**myArr));

Upvotes: 1

Related Questions