c# - string[,] array of string arrays equivalent in C -


in c#, if create array of string arrays easy doing:

string[,] array = new string[50,7]; 

how go doing in c? understand should make use of pointers have come doesn't seem work properly.

char *array[50][7]; 

please note i'm not looking set elements constant values, need able access them/set them in program again either means of using scanf() function or = if possible. simplest way of achieving this?

edit: doing wrong here? following simple example crashes program:

char *username;  printf("username: "); scanf("%s", &username);  array[0][0] = malloc(strlen(username) + 1); strcpy(array[0][0], username); 

i have, in fact, added reference stdlib.h

the following code crashes code attempting save scanf() input place pointed username, yet username not initialized.

char *username; scanf("%s", &username);  // bad 

instead, use

char username[100]; scanf("%99s", username); 

or better

char username[100]; fgets(username, sizeof username, stdin); username[strcspn(username, "\n")] = '\0';  // lop off potential \n 

it appear op wants 50 x 7 array of pointers c strings allocated in string[,] array = new string[50,7];

recall, in c, string character array ending null character

#include <stdlib.h> typedef char *a50_7_t[50][7];  a50_7_t *a50_7_alloc(void) {   a50_7_t *a = malloc(sizeof *a);   (int i=0; i<50; i++) {     (int j=0; j<7; j++) {       (*a)[i][j] = null;  // or whatever op wants initial state     }   }   return a; }  void a50_7_free(a50_7_t *a) {   (int i=0; i<50; i++) {     (int j=0; j<7; j++) {       free((*a)[i][j]);     }   }   free(a); }  // sample usage code #include <string.h> void foo(void) {   a50_7_t *a = a50_7_alloc();   printf("size %zu\n", sizeof *a);   // e.g. "size 1400"   (*a)[0][0] = strcpy(malloc(6), "hello");   a50_7_free(a); } 

otoh if op want create array part of declaration, op did on right track.

//                   initialize zeros, (null) char *array[50][7] = { 0 }; ... array[0][0] = strcpy(malloc(6), "hello"); ... free(array[0][0]); 

Comments

Popular posts from this blog

ruby - Trying to change last to "x"s to 23 -

jquery - Clone last and append item to closest class -

c - Unrecognised emulation mode: elf_i386 on MinGW32 -