开发者

Dynamic 2d array is not creating properly

I want to create a dynamic 2d array by function but it seems that something is very wrong. It throws me an error when I want to put something in it.

Error

Unhandled exception at 0x003a19c8 in p01.exe: 0xC0000005: Access violation writing location 0xcdcdcdcd.

CreateDynamicArray()

short int** CreateDynamicArray(int row, int col)
{
    // Creating variable
    short int** dynamicArray;

    // Creating rows
    dynamicArray = (short int**)malloc(row * sizeof(short int*));

    // Going trough every row and creating columns for them
    for (int i = 0; i < row; i++)
    {
        dynamicArray[row] = (short int*)malloc(col * sizeof(short int));
    }

    // Returning created array
    return dynamicArray;
}

main()

// Creating it
dynamicArray = CreateDynamicArray(row, col);

// Filling up with random numbers
for (i = 0; i < row; i++)
{
    randomNumber = rand() % 20;
    dynamicArray[i][n] = randomNumber; // Here it th开发者_运维知识库rows me exception
    for (n = 0; n < col; n++)
    {
        randomNumber = rand() % 20;
        dynamicArray[i][n] = randomNumber;
    }
}

Dynamic 2d array is not creating properly

P.S. Yes, this is somewhat of a homework, but I still need help om this matter :)


change row to i.

short int** CreateDynamicArray(int row, int col)
{
    // Creating variable
    short int** dynamicArray;

    // Creating rows
    dynamicArray = (short int**)malloc(row * sizeof(short int*));

    // Going trough every row and creating columns for them
    for (int i = 0; i < row; i++)
    {
        dynamicArray[i] = (short int*)malloc(col * sizeof(short int));
    }

    // Returning created array
    return dynamicArray;
}


Apart from what Gunner said, the n variable is used for the loop, but the line where the exception is thrown also uses the n variable. I think you have a logic error:)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜