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;
}
3
  • 2
    They say you shouldn't cast the result of malloc(). Commented Dec 15, 2015 at 15:49
  • 1
    casting the return of malloc() and family is required only in C++, however not recommended in C. Commented Dec 15, 2015 at 15:51
  • 1
    if (i >=lines) will never execute Commented Dec 15, 2015 at 15:51

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.