Question

I successfully wrote a C++ code for radix sort by creating 10 buckets. For the 10 buckets, I created them in this way:

struct node{
    struct node* next;
    long value;
};

struct node*bucket[10];

for (int i=0; i<10; ++i) {  
    bucket[i] = (struct node *) malloc (1000000*sizeof(struct node));
}

and it is perfect done.

But then now I need to raise the amount of my buckets to 100000. I tried to modified those buckets' size like:

struct node*bucket[100000];

for (int i=0; i<100000; ++i) {  
    bucket[i] = (struct node *) malloc (1000000*sizeof(struct node));
}

But this time I think I can't even create those buckets. I am using Visual Studio to code, and this is in C++. The compiler gave me these warnings:

: warning C4305: 'argument' : truncation from '__int64' to 'size_t'

: warning C4309: 'argument' : truncation of constant value

I searched it up in the internet, somebody says the number is too big. This is the first time I handle such a large number in the linked list. Do I need to modify anything to make this code work again?

Thank you. Any ideas and help I will be appreciated!

Was it helpful?

Solution

I turned your code into a little sample program:

#include <stdlib.h>

struct node {
    int i;
};

int main()
{
    struct node*bucket[100000];

    for (int i=0; i<100000; ++i) { 
        bucket[i] = (struct node *) malloc (1000000*sizeof(struct node));
    }
}

This compiles nicely with Visual Studio 2010.

What comes to my mind is that you're allocating an array of 100000 pointers (probably 4 bytes each). It reminds me of old compilers which wouldn't let you use more than 64kB of stack space per variable (or function? I cannot remember. It was with Turbo Pascal or Turbo C...).

Since this is C++, I suggest to just not use a raw C array in the first place. Instead, you can replace the above code with:

#include <vector>

struct node {
    int i;
};

int main()
{
    std::vector<node> bucket( 100000 );
}

The std::vector object can be used in all cases where you'd use a C array.

OTHER TIPS

Probably the problem is in the loop condition:

for (int i=0; i<100000; ++i)
              ^^^^^^^^^

You need to have std::size_t i; or unsigned long i; to compare till 100000.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top