user5744341
user5744341

Reputation:

Array of strings with no malloc in c

Can someone tell me whats wrong with that code?And i cant use malloc because i havent learn it in class.I mean can i make a 2d array of strings without malloc and if yes how i am i supposed to write an element when i want to change it/print it/scan it.Thanks in advance

int main() {

    size_t x,y;
    char *a[50][7];

    for(x=0;x<=SIZEX;x++)
    {
        printf("\nPlease enter the name of the new user\n");
        scanf(" %s",a[x][0]);

        printf("Please enter the surname of the new user\n");
        scanf(" %s",a[x][1]);

        printf("Please enter the Identity Number of the new user\n");
        scanf(" %s",a[x][2]);

        printf("Please enter the year of birth of the new user\n");
        scanf(" %s",a[x][3]);

        printf("Please enter the username of the new user\n");
        scanf(" %s",a[x][4]);

    }

    return 0;
}

Upvotes: 0

Views: 904

Answers (2)

alk
alk

Reputation: 70981

can i make a 2d array of strings without malloc

Sure. Let's reduce this to 2*3:

#include <stdio.h>

char * pa[2][3] = {
   {"a", "bb","ccc"},
   {"dddd", "eeeee", "ffffff"}
  };

int main(void)
{
  for (size_t i = 0; i < 2; ++i)
  {
    for (size_t j = 0; j < 3; ++j)
    {
      printf("i=%zu, j=%zu: string='%s'\n", i, j, pa[i][j]);
    }
  }
}

Output:

i=0, j=0: string='a'
i=0 j=1: string='bb'
i=0, j=2: string='ccc'
i=1, j=0: string='dddd'
i=1, j=1: string='eeeee'
i=1, j=2: string='ffffff'

Upvotes: 0

Paul92
Paul92

Reputation: 9082

So, you need a 2d array of strings (char arrays). One way to achieve this would be to allocate a 3d array of char as:

char x[50][7][MAX_LENGTH];

You can think as having a matrix of array start (of pointers) and then, another dimension to give depth to your matrix (i.e. storage space for your string).

Your approach is also fine, as long as you are willing to allocate manually using malloc or similar storage space for your strings.

Upvotes: 2

Related Questions