c - 类型 "void *"的值不能分配给类型 "int **"最后的实体

标签 c memory malloc

我正在制作一个动态创建二维数组的程序。但是它显示了我在标题中提到的错误。我正在使用 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++ 中,当将 void * 指针分配给另一种类型的指针时,您需要进行强制转换。但是在 C++ 中你不应该使用 malloc(),而是使用

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

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

正如@KeineLust指出的,你的分配也是错误的here .

关于c - 类型 "void *"的值不能分配给类型 "int **"最后的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42824383/

相关文章:

c - 如何再次正确地重新分配一个 free() 的结构?

c - 免费 - SP16 缓冲器

javascript:通过循环内联加速 10 倍?

c# - .Net 内存跟踪中的 "TargetCore"是什么?

C - 像这样使用 malloc 有什么问题?

c++ - 如何知道何时释放内存?

c - 在 C 编程方面需要一些帮助

c - 使 printf 仅打印 n 字节整数的前 x 字节

Mysql根据前缀计算总内存

c - 在C语言中,如何将节点添加到列表的开头?