wis.niowy
wis.niowy

Reputation: 87

C: Array initialization requires a brace-enclosed initializer list

I'm just a beginner and have encountered a problem with an array of pointers. Could you show me where the mistake is?

int ini()
{
    int *tab[N];
    int i, j, a, b;
    for (i = 0; i < N; i++)
    {
        tab[i] = (int*)malloc(M*sizeof(int));
    }
    if (tab == NULL)
        return -1;
    scanf_s("%d  %d", &a, &b);
    for (i = 0; i < N; i++)
    {
        for (j = 0; j < M; j++)
        {
            *(*(tab+i)+j) = rand() % (b - a + 1) + a;
        }
    }
    return tab;
}

int main()
{
    int i, j, *tablica[N] = ini();
    for (i = 0; i < N; i++)
    {
        for (j = 0; j < M; j++)
        {
            printf("%d  ", *(*(tablica+i) + j));
        }
        printf("\n");
    }
    system("PAUSE");
    return 0;
}

The task itsef is simple and I can do it in the other way, but I just wanted to use this:

*(*(tab+i)+j)

instead of that:

*(tab + N*i + j)

since the second option wouldn't always work.

I'll be glad if you could give me a hand. :)

Upvotes: 0

Views: 2616

Answers (2)

wis.niowy
wis.niowy

Reputation: 87

I wanted to upgrade that program (and to make it work in the same way):

int ini()
{
int *tab;
int i, j, a, b;
for (i = 0; i < N; i++)
tab = (int*)malloc(N*M*sizeof(int));
if (tab == NULL)
    return -1;
scanf_s("%d  %d", &a, &b);
for (i = 0; i < N; i++)
{
    for (j = 0; j < M; j++)
    {
        *(tab + N*i +j ) = rand() % (b - a + 1) + a;
    }
}
return tab;
}


int main()
{
int i, j, *tablica = ini();
for (i = 0; i < N; i++)
{
    for (j = 0; j < M; j++)
    {
        printf("%d  ", *(tablica + N*i + j));
    }
    printf("\n");
}
system("PAUSE");
return 0;
}

Upvotes: 0

Ashalynd
Ashalynd

Reputation: 12563

A couple of obvious things:

  • you return a locally declared array (int *tab[N];) outside of its scope, therefore it's going to be garbage there. This must be your most visible problem.

  • you malloc the elements of that array inside your ini() method but never release them, therefore you are getting a memory leak.

  • checking tab for NULL does not make much sense, because tab would never be NULL; tab[i], on the other hand, can be NULL and could be checked for that after malloc.

  • you don't check that your tablica is not -1.

Upvotes: 1

Related Questions