0

I am trying to fill a multidimensional array with chars.

The task is: I need to fill 30 names in array, each name could not be longer than 20.

char names_arr[NAME_BUF_SIZE][MAX_NAME_LENGTH];

So, I wrote such a method:

void read_from_input(char arr[][MAX_NAME_LENGTH])
{
    unsigned r = 0;
    int i = 0, j = 0;
    char tmp[MAX_NAME_LENGTH];

    for (i = 0; i < NAME_BUF_SIZE /*30*/; i++)
    {
        for (j = 0; j < MAX_NAME_LENGTH /*20*/; j++)
        {
            if((r = scanf("%s", tmp) != EOF) && (r != 0))
            {
                arr[i][j] = tmp;
            }
        }
    }
}

Such a way I would like to fill my array with names.

But the issue is that I get a such warning

main.c: In function ‘read_from_input’:
main.c:31:27: warning: assignment makes integer from pointer without a cast [-Wint-conversion]
                 arr[i][j] = tmp;
                           ^

What am I doing wrong?

7
  • What is the purpose of tmp array? Here arr[i][j] = tmp; you're trying yo assign the array to the element of second array. Commented Dec 21, 2019 at 12:56
  • 1
    arr[i][j] is a char, and you are assigning to it tmp that is a char array, that is actually a pointer to the first char of the array. Commented Dec 21, 2019 at 12:58
  • 2
    Given that those are string, consider using strcpy. Commented Dec 21, 2019 at 13:24
  • 1
    Also, in real application, if you use scanf, always limit the size of the input to avoid buffer overruns (e.g.: "%19s"). Commented Dec 21, 2019 at 13:25
  • 1
    Aleksey, strcpy is ok. And about the suggestion above, an array of 20 chars can contain a string long up to 19chars because uone of them is the stringo terminator '\0'. Commented Dec 21, 2019 at 14:27

1 Answer 1

1

Perhaps this is what you mean to do:

for (i = 0; i < NAME_BUF_SIZE; i++) {
    if((r = scanf("%19s", tmp) != EOF) && (r != 0)) {
        strcpy(arr[i], tmp);
    }
}

First of all, in your original code, you're trying to assign tmp (char *) to arr[i][j] (char). If arr is an array of words, then each a[i] will be a word (char*) and each a[i][j] will be a letter (char). Not only that, but that is not the correct way to copy a string.

This is how you should copy a string in C:

strcpy(arr[i], tmp);

Hope this helped!

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.