Home > Back-end >  C loop to get strings and store them in 2D array
C loop to get strings and store them in 2D array

Time:12-03

I created a multi-dim array to store (name/fname/code) of multiple students in (row 0) it stores the (name/fname/code) of the first student then it passes to the next row (row 1) --> (name/fname/code) of the second student ... etc.

Every time I run the code and write a string when it reaches 9 character it will add 8 char of the next string and if the next string reaches 9 char it will add 8 char of the next string to it.

But if I write the name with just 8 char or less it runs like I want to.

If you didn't understand run the code and you will get it.

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

int main() {

  int i, nmbStud;

  int rows, columns;

  printf("Enter the number of students you want to add : ");
  scanf("%d", &nmbStud);

  char *arr[nmbStud][256];

  for (rows = 0; rows < nmbStud; rows  ) {
    columns = 0;
    while (columns < 3) {

      printf("--Enter the %d name : ", rows   1);
      scanf("%s", &arr[rows][columns]);

      columns  ;

      printf("--Enter the %d family name : ", rows   1);
      scanf("%s", &arr[rows][columns]);

      columns  ;

      printf("--Enter the code of the student %d : ", rows   1);
      scanf("%s", &arr[rows][columns]);

      columns  ;
    }
  }

  for (rows = 0; rows < nmbStud; rows  ) {
    for (columns = 0; columns < 3; columns  ) {
      printf("-->%s\n", &arr[rows][columns]);
    }
  }
}   

Compile result

CodePudding user response:

The rule is that you should correctly declare what you need and use it accordingly. Here char *arr[nmbStud][256]; declares a Variable Length Array of pointers to characters. But later you use it with:

        scanf("%s",&arr[rows][columns]);

which stores the characters inside the pointer value. As you have a 64 bits system, a pointer uses 8 bytes, hence the problem when you try to use strings using more than 7 characters - do not forget the terminating null in C strings!

What you want should be closer to:

char arr[nmbStud][3][256]; // 2D VLA, size nmStud * 3, of strings of 255 characters

and later:

        scanf("%s",arr[rows][columns]);

And you should be aware that this code uses VLA which is an optional feature since C11 and that will not be accepted for example by Microsoft compilers...


But as the 3 strings contain different elements you'd better use structs here:

struct Student {
   char name[256];
   char fname[256];
   char code[256];
};
  • Related