0

I am new in C and I am trying to create a 2D array of chars. The logic behind this is to get unknown amount of string inputs from the user and to be able to get to those strings (each string ends with a ":") but when I tried to debug I got:

<Error reading characters of string>

This is the code:

int main()
{
    int j = 0, rows = 50;
    int i=0, lines = 50;
    char **names;

    names = (char**)malloc(lines*sizeof(char*));

    if (i >= lines)
    {
        names = (char**)realloc(names, 10 * sizeof(char*));
        lines = lines * 10;
    }

    for (j ; names[i][j] != ':'; j++)
    {
        *names = (char*)malloc(rows * sizeof(char));

        if (j >= rows)
        {
            *names = (char*)realloc(names, 10 * sizeof(char));
            rows = rows * 10;
        }
        scanf("%c", &names[i][j]);
    }
    i++;
    return 0;
}
dragosht
  • 3,237
  • 2
  • 23
  • 32
yarden95c
  • 11
  • 2

1 Answers1

1
for (j ; names[i][j] != ':'; j++)

In this loop your test condition tests for ':' in names . names has been allocated memory but it does not contain any content (what will it compare to ?).

Use a do-while loop , in order to execute loop before reading characters in names.

Also you allocate memory for char *'s but you don't allocate memory to these pointers correctly . And without allocating memory correctly you try to store characters at location they point to . This will cause problem .

Allocate memory to each char * and then take input .

Some this like this can be done -

do{
     names[i] =malloc(rows * sizeof(char));
     if(names!=NULL){
      if (j >= rows) 
        {
           *names = (char*)realloc(names, 10 * sizeof(char));
           rows = rows * 10;
        }
       scanf("%c", &names[i][j]);
       j++;
       i++;
    }
}while(names[i][j]!=':')'

Note-

1. You should free the allocated memory . And you first if will not execute (can't understand its use ).

2. Check return of malloc.

ameyCU
  • 16,489
  • 2
  • 26
  • 41