我正在制作一个动态创建二维数组的程序。但是它显示了我在标题中提到的错误。我正在使用 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。
关于c - 类型 "void *"的值不能分配给类型 "int **"最后的实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42824383/