PDA

Click to See Complete Forum and Search --> : Help with my homework please


Crazy_bee
Jan 29th, 2002, 12:02 PM
I have to create a simple counting sort:

#include "stdafx.h"
#include "stdlib.h"
int main(int argc, char* argv[])
{
int *x;
int a[10] = {23,2,53,6,98,52,43,76,3,11};
int b[10];
int max=0;
int i;
int amount;
int i2;
int bi;

/*Finds the maximum number in the array*/
for(i=0;i<10;i++)
{
if(a[i]>max)
max=a[i];
}


x = calloc(max, sizeof(int));/*allocates the memory for dynamic array*/

/*counts the number of reoccurances and places them into correct index of array c*/
for(i=0;i<max;i++)
{
amount = 0;
for(i2=0;i2<10;i++)
{
if(a[i2]==i)
amount++;
}
x[i] = amount;
}

/*loops through array c and enters anything with one or more occurrances into array b*/
for(i=0;i<max;i++)
{
if(x[i]!=0)
{
for(i2=0;i2<x[i];i2++)
{
b[bi]=i;
bi++;
}
}
}

/*prints the count sorted array*/
printf("This is count sorted array:\n");
for(i=0;i<10;i++)
{
printf("d2\n",b[i]);
}
return 0;

}

when i compile i get the following error can anyone figure this out, Ive been staring at it for 2 hours.:confused:

C:\My Documents\Test\test.cpp(25) : error C2440: '=' : cannot convert from 'void *' to 'int *'
Conversion from 'void*' to pointer to non-'void' requires an explicit cast
Error executing cl.exe.


Thank you

chilibean
Jan 29th, 2002, 02:59 PM
I reformatted your code and fixed the errors, but I don't think it does what you intended to do.

The problem was that you needed to initialize your variables and one of your loop counters was messed up.



#include <stdio.h>
#include <malloc.h>

int main(int argc, char* argv[]){

int *x;
int a[10] = {23,2,53,6,98,52,43,76,3,11};
int b[10];
int max=0;
int i=0;
int amount=0;
int i2=0;
int bi=0;

/*Finds the maximum number in the array*/
for(i=0;i<10;i++){
if(a[i]>max)
max=a[i];
}


x = (int *)calloc(max, sizeof(int));/*allocates the memory for dynamic array*/

/*counts the number of reoccurances and places them into correct index of array c*/
for(i=0;i<max;i++){

amount = 0;

for(i2=0;i2<10;i2++){
if(a[i2]==i)
amount++;
}

x[i] = amount;
}

/*loops through array c and enters anything with one or more occurrances into array b*/
for(i=0;i<max;i++){

if(x[i]!=0){
for(i2=0;i2<x[i];i2++){
b[bi]=i;
bi++;
}
}
}

/*prints the count sorted array*/
printf("This is count sorted array:\n");
for(i=0;i<10;i++){
printf("d2\n",b[i]);
}
return 0;

}