Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Strange warning massage

Status
Not open for further replies.

qzou666

Programmer
Feb 12, 2002
11
0
0
NZ
Hi,

I have a function as follow:

void ClassA::FunctionA()
{
float* a
a = new float[5];
}

The Visual C++ compiler keeps giving the following warning massages:

warning C4305: 'initializing' : truncation from 'int' to 'short'
warning C4309: 'initializing' : truncation of constant value

Could anyone tell me what caused the warnings?

Thanks a lot
 
Strange warning message? Instead, I'd say, strange class. Here's what I think is happening...
Code:
void ClassA::FunctionA()
{    
  float* a
  a = new float[5];
}
You create a single variable pointer of type "float", called 'a'. Given that you've only got a single pointer, the next line should only allocate a single float object. Instead, you attempt to allocate 5. And because you don't cast the object(s) that are being created, the new operation creates integer object(s) as a default. Here's a corrected version of your class:
Code:
void ClassA::FunctionA()
{    
  float* a
  a = (float*)new float;
}
 
Now, if your intent is to create 5 float objects, then do something like this:
Code:
void ClassA::FunctionA()
{
  float* a[5];
  int i = 0;

  // initialize pointers to NULL
  for (i = 0; i < 5; i++)
  {
    a[i] = NULL;
  }

  // create float objects
  for (i = 0; i < 5; i++)
  {
    a[i] = (float*)new float;
    // you probably should be checking for
    // allocation failure; that's up to you.
  }

  // ...then use the float objects...

  // finally, don't forget to delete them
  for (i = 0; i < 5; i++)
  {
    if (a[i] != NULL)
    {
      delete (a[i]);
      a[i] = NULL;
  }
}
 
Thanks, programsecrets.

I think the statement is OK since float is a basic type, not a class.

float* a; (sorry, I missed ';')
a = new float[5];

In fact, there are a large number of similar functions in the same class, and most of them do not cause the warning masssages.

Cheers.
 
Sorry for the overkill. I was just trying to think of some ideas...

I'm glad you solved your own problem. :)
 
Which version of MS VC compiler are you using...

Anand ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Mail me at abpillai@excite.com if you want additional help. I dont promise that I can solve your problem, but I will try my best.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
I don't see any problem with that code. Are you sure that is the line of the warning?

Shyan
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top