【问题标题】:a value of type "void *" cannot be assigned to an entity of type "int **" last“void *”类型的值不能最后分配给“int **”类型的实体
【发布时间】:2017-03-16 02:45:58
【问题描述】:

我正在制作一个动态创建二维数组的程序。但它显示了我在标题中提到的错误。我正在使用 Visual Studio 2015。

// last.cpp : 定义控制台应用程序的入口点。 //

#include "stdafx.h"
#include <stdio.h>
#include <time.h>
#include "stdlib.h"

double selectionSort(int * number, int number_count);
void print2d(int ** array, int rows, int cols);
void twodarray();

void main(int argc, char* argv[])
{
    int num_count = 10000;
    int num[10000];
    for (int i = 0; i < num_count; i++)
    {
        num[i] = rand();
    }
    double sortTime = selectionSort(num, num_count);
    printf("Total Runtime is: %.0f milliseconds. \n", sortTime * 1000);
    twodarray();
    getchar();
}

double selectionSort(int * number, int number_count)
{
    clock_t start, end;
    double duration;
    int min;
    start = clock();
    for (int i = 0; i < number_count - 1; i++)
    {
        min = i;
        for (int j = i + 1; j < number_count; j++)
        {
            if (number[min] > number[j])
            {
                min = j;
            }
        }
        if (min != i)
        {
            int temp = number[min];
            number[min] = number[i];
            number[i] = temp;
        }
    }
    end = clock();
    return duration = (double)(end - start) / CLOCKS_PER_SEC;
}

void print2d(int ** array, int rows, int cols)
{
    int i, j;
    for (i = 0; i < rows; i++)
    {
        for (j = 0, j < cols; j++;)
        {
            printf("%10d ", array[i][j]);
        }
        puts("");
    }

}


void twodarray()
{
    int **twod;
    int rows = 10;
    twod = malloc(rows * sizeof(int));
    int i,cols = 10;
    for (i = 0; i < rows; i++)
    {
        twod[i] = malloc(cols*sizeof(int));
        print2d(twod, rows, cols);
    }

    for (i = 0; rows; i++)
    {
        free(twod[i]);
        free(twod);
    }
}

【问题讨论】:

标签: c memory malloc


【解决方案1】:

在 c++ 中,将 void * 指针分配给另一种类型的指针时需要进行强制转换。但是在c++中你不应该使用malloc(),而是使用

int **twod = new int *[rows];

如果您不是要编写 c++ 程序,请重命名文件。将扩展名从 .cpp 更改为 .c

正如@KeineLusthere所指出的,你的分配也是错误的。

【讨论】:

    【解决方案2】:

    这是错误的:

    int **twod;
    int rows = 10;
    twod = malloc(rows * sizeof(int));
    

    你需要为n个指向int的指针预留空间,而不是为n个ints,改为

    twod = malloc(rows * sizeof(int *));
    

    这里:

       for (j = 0, j < cols; j++;)
                 ^              ^
    

    使用分号代替逗号,并删除最后一个分号。

    另一个问题:

    for (i = 0; rows; i++)
    {
        free(twod[i]);
        free(twod); /* Don't free twod in the loop, one malloc -> one free */
    }
    

    正如 Nicat 和 Iharob 所指出的,您似乎在混合使用 C 和 C++,请使用正确的扩展名 (.c)

    【讨论】:

    • 我完成了所有更改,但仍然无法正常工作。
    猜你喜欢
    • 1970-01-01
    • 2018-02-17
    • 1970-01-01
    • 1970-01-01
    • 2014-03-23
    • 1970-01-01
    • 1970-01-01
    • 2013-04-02
    • 2019-03-27
    相关资源
    最近更新 更多