user4222907
user4222907

Reputation:

How to dereference multidimensional Array in C programming?

I want to pass a pointer to a multidimensional Array, so the value could be kept not copied. How can I do it? I also keep tracking the int count, will it work every time? The array that I need is memory. The struct has been declared before, outside the main.

struct registers
{
   int data;     
} registerX, registerY;

void first(int *counter, struct registers* X1, int **m)
{
  int value;
  printf("Enter the value for the X\n");
  scanf("%d", &value);
  X1->data = value;
  m[*counter][1] = X1->data;
  *counter = *counter++;

}
int main()
{
 int memory[SIZE][2];
 int count = 0;
 int choice;
 printf("Enter the instruction number:\n");

 while(choice != 107)
{
  scanf("%d", &choice);
  if(choice == 101)
  {
        memory[count][0] = 101;
        first(&count, &registerX, &memory[count][1]);
  } 

Upvotes: 0

Views: 279

Answers (2)

Patricio S
Patricio S

Reputation: 2130

  • First of all, apart from what Kerrek SB said, you could replace

    *counter = *counter++;
    

    with this

    (*counter)++;
    

    EDIT: Sorry, I made a mistake trying to say what's wrong with *counter = *counter++, but I got some strange results with the sentence *pointer = *pointer++.

  • Second, I see that you are using registerX while it's just a type, so you could first do this.

    registerX *rgx = NULL;
    rgx = malloc(sizeof(registerX));
    

    and use.

    first(&count, rgx, memory);
    

Considering what I said above, this code worked for me.

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

#define SIZE 5

typedef struct registers {
    int data;     
} registerX, registerY;

void first(int *counter, struct registers *X1, int m[][2]) {
    int value;

    printf("Enter the value for the X: ");
    scanf("%d", &value);

    X1->data = value;
    m[*counter][1] = X1->data;

    (*counter)++;

    return ;
}

int main() {
    int memory[SIZE][2];
    int count = 0;
    int choice;

    registerX *rgx = NULL;
    rgx = malloc(sizeof(registerX));

    printf("Enter the instruction number: ");

    while(choice != 107) {
        scanf("%d", &choice);

        if (choice == 101) {
            memory[count][0] = 101;
            first(&count, rgx, memory);
            printf("Number %d was stored in memory[%d][%d]\n\n", memory[count-1][1], count-1, 1);
        }

        printf("Enter more instructions: ");
    }

    return 0;
}

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 476940

The function signature should be:

void first(int *counter, struct registers* X1, int m[][2])

Or equivalently:

void first(int *counter, struct registers* X1, int (*m)[2])

The call should be:

first(&count, &registerX, memory);

Upvotes: 2

Related Questions