Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

a value of type "void *" cannot be assigned to an entity of type "int **" last

Tags:

c

memory

malloc

I'm making a program which dynamically creating 2d array.but it's showing the error which I mentioned on the title. I'm using Visual Studio 2015.

// last.cpp : Defines the entry point for the console application. //

#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);
    }
}
like image 715
Nicat Muzaffarli Avatar asked Sep 20 '25 17:09

Nicat Muzaffarli


1 Answers

In c++ you need to cast when assigining a void * pointer to another type of pointer. But in c++ you should not use malloc(), instead use

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

If you didn't mean to write a c++ program, rename the file. Change the extension from .cpp to .c.

Your allocation is wrong too, as pointed out by @KeineLust here.

like image 93
Iharob Al Asimi Avatar answered Sep 22 '25 08:09

Iharob Al Asimi