-1
void ArrayCal();

int main(void)
{
    ArrayCal();//calling fun.
    return 0;
    system("pause");
}

void ArrayCal()//this fun will scan elements into (Arr) the array of pointer
{
    int a = 0, b = 0, c = 0, row = 0;
    printf("Enter numbers of rows: ");
    scanf("%d", &row);//scan rows
    int* Arr = (int*)malloc(sizeof(int)*row);//to add more memory into the Arr
        for (a = 0; a < row; a++)
        {
            printf("\nEnter array length for row %d: ", a + 1);
            scanf("%d", &b);//scan length
            *(Arr + a) = (int*)malloc(sizeof(int)*b);//to add more memory into the arrays

            for (c = 0; c < b; c++)
            {
                printf("\nEnter value for array: ");
                scanf("%d", Arr[row][b]);//scan value
            }
        }
    sortPrint(Arr);//calling fun. to print the Arr

    free(Arr);//to free the memory of the Arr.
    for (a = 0; a < row; a++)
    {
        free(*(Arr + a));//to free the memory of the arrays 
    }
}

I'm trying to scan elements into array of pointer and I don't know why I have this bug.

unwind
  • 391,730
  • 64
  • 469
  • 606
TeviXor
  • 5
  • 1
  • 3
  • You forgot to mention __where__ the error occurs. And it's not a bug, it's a compilation error. – Jabberwocky May 12 '17 at 08:35
  • You should never cast the result of malloc. – Badda May 12 '17 at 08:40
  • 1) `int* Arr = (int*)malloc(sizeof(int)*row);` --> `int** Arr = (int**)malloc(sizeof(int*)*row);` – BLUEPIXY May 12 '17 at 08:41
  • Unfortunately, it seems likely that you are using a bad source for learning C programming, who is trying to "teach" you how to "dynamically allocate 2D arrays". – Lundin May 12 '17 at 08:51
  • Also, you need to get a better compiler or enable warnings on the one you are using. Code such as `return 0; system("pause");` shouldn't pass without warnings on any half-decent compiler. – Lundin May 12 '17 at 08:53
  • You need to have `int **Arr` for that to work; also; you're using the `Arr` after it has been freed which is a *grave* error. Also `Arr[row][b]`, even when `Arr` is a double-star, isn't a pointer, and `scanf` wouldn't work. All in all, how could you write all of this code when even the simpler parts wouldn't compile there - please try to compile more often in the beginning. – Antti Haapala -- Слава Україні May 12 '17 at 08:54

1 Answers1

1

This is not how you allocate pointer-based look-up tables. You need to allocate an array of pointers first, and then set every pointer in that array to point at allocated memory.

The code in the question of Correctly allocating multi-dimensional arrays shows how to allocate this properly. However, as the answer to that question demonstrates, this is most likely the wrong method to use in the first place.

Community
  • 1
  • 1
Lundin
  • 195,001
  • 40
  • 254
  • 396