C++ :: Getting Surprising Behavior When Casting
Mar 18, 2014
I'm trying to cast a float to an unsigned int and getting some surprising behavior.
Code:
float x = -1.0;
unsigned int y = (unsigned int)x;
printf("y = %d
", y);
The output of this code changes depending on which compiler I use. Sometimes I get -1 and sometimes I get 0. Not really sure why though.
View 5 Replies
ADVERTISEMENT
Apr 1, 2014
I have a WordRecord that contains a LinkedList (both my doing). I have rigorously tested my LinkedList class, and know that it works (heck, I used it in the last project I had!). The problem is that undefined behaviour seems to happen when using the WordRecord, which has a std::string and a LinkedList<unsigned>. (The problem happens with the LinkedList.)
Here is the code:
main.cpp
#include <iostream>
#include "BinaryTreeNode.h" // here for test purposes
#include "LexicographicTree.h"
#include "LinkedList.h"//also for test purposes
#include "OutputStream.h"
#include "WordRecord.h"
using namespace std;
int main()
{
// setup the OutputStream to print to "test.txt"
OutputStream stream("test.txt");
// create a sampleWordRecord (make it have the word "I" on line 1)
[code]....
One of the requirements for the project is that it must compile on Unix server (I am using Windows, and have tested it in both environments.) I get a core-dump in the Unix environment. On the other hand, the output on-screen in the Windows environment looks right. However, when I open up the text file, I get the following
Sample word record:
WordLines
I{14}
/* I have no what is happening to sampleWordRecord's LinkedList; I am not trying to modify it, except for where I created the sampleWordRecord! */
View 14 Replies
View Related
Aug 29, 2014
There is a list control in Windows.
When I create a list control I can assign an image list to it with the ListView_SetImageList().
By default, when just created there is no image list assigned as can be checked with ListView_GetImageList().
Now, what should happen when I do following call:
Create list control.
Create an image list
Get the current image list
Assign an image list to list control
Display some items
Assign an old image list to list control.
Does strings on the list control should be indented?
View 4 Replies
View Related
Oct 31, 2013
There was an "impovement" since Windows 7 in algorithm for selecting the initial directory, which is described here OPENFILENAME structure. Briefly:
Windows 7:
If lpstrInitialDir has the same value as was passed the first time the application used an Open or Save As dialog box, the path most recently selected by the user is used as the initial directory. Otherwise, if lpstrFile contains a path, that path is the initial directory.
Otherwise, if lpstrInitialDir is not NULL, it specifies the initial directory. If lpstrInitialDir is NULL and the current directory contains any files of the specified filter types, the initial directory is the current directory. Otherwise, the initial directory is the personal files directory of the current user. Otherwise, the initial directory is the Desktop folder.
The problem that this behavior is not what users of my program expect. Another constraint is that I need to use old CFileDialog dialog, not Common File Dialogs. I've tried to use advises described on StackOverflow and on MSDN. This solution by EllisMiller works perfectly:
Specifying a full path (including filename) in lpstrFile. The filename of course shows up in the filename box which is annoying. I ended up using a filename of "." and adding a bit of code to clear the filename combobox once the dialog is open.
BUT I can't figure how to clear the filename combobox. I've tried to add hook procedure, enumerate windows and clear text, but this didn't work for me. So, my question is: how can I clear text in the filename combobox of CFileDialog?
View 12 Replies
View Related
Jun 8, 2013
Let's say I have a product that needs service after 500 hours at 100 RPM. I can dsiplay the remaining hours only as an integer and we only have integer math. Management wants it to display 500 for the first hour, not 499 after the first minute is ticked off. But after a few minutes fullHours will be 499 and partialHours will have some value. I have 3 ways to determine displayHours to suit management and I want to know if the first is ligit.
short fullHours = 500;
short partialHours = 0;
short displayedHours = 0;
// Method 1 - Is is Kosher to cast a boolean as an int? Is TRUE always a 1 or is that a bad assumption?
displayedHours = fullHours + (short) (partialHours != 0);
//Method 2 - Works but some have disdain for the ternary conditional
displayHours = fullHours + (partialHours ? 1 : 0);
//Method 3 - seems a bit pedantic
displayHours = fullHours;
if (partialHours != 0) {
displayHours++;
}
View 19 Replies
View Related
Apr 12, 2013
I find type casting to be very hard to grasp, I am not sure why. I understand how it works I suppose, but I find it hard to grasp why it would be needed in programming. So my question is, how often is type casting used in general programs? Is there an easier way I could be trying to teach myself about it? I am just using the tutorials provided by this site.
View 2 Replies
View Related
Apr 30, 2014
I'm writing a small piece of code that increments through a string of numbers. For every 5 numbers a product is produced. However i'm having an issue understanding an error that keeps occurring.
#include <iostream>
#include <string>
#include <cstdlib>
[Code].....
if you look at the code i've got a string with 5 numbers 1-5 for testing. As the loop increments through the string it takes the first 5 characters and converts them to integers and then a product is returned. The issue is that instead of storing the single letter at position J its storing some combination from the string and as a result gives me a huge product. I tried debugging. I checked what the string[j] value was with a simple cout << and it returned the right number. I even returned the char value before it was converted into an integer and it was the right number.
View 3 Replies
View Related
Jan 3, 2015
double a = 1.0 + 1 + 1.0f; //everynumber will be added up as a double even the last one which is a float. All 3 numbers will turn into 3.0 as a double.
int x = (int)(7 + 3.0 / 4.0 * 2); //the variable will do the math bracket first. then the va type will still be an int because int was never changed.
Console.WriteLine((1 + 1) / 2 * 3); // 1 + 1 will be done first then 1 / 2 then * by 3
Console.WriteLine(x);
Console.ReadKey();
I THINK THATS ALL WRONG ^ =/ like the comments
double a = 1.0 + 1 + 1.0f;
In this equation, everything is using addition, so we start working left to right. 1.0 + 1 is the first step. These two representations of 1 aren't the same type though. In fact, none of the three are.
The first is a double, the second is an int, and the last is a float.
So in order to do 1.0 + 1, we need to convert one type to another. Since the double type is "wider" than the int type, we'll move things up to the double type. We'll convert the int version to a double, and to 1 + 1 using double types, resulting in 2.0 as a double.
Next we do the other addition. This has the same problem, though, because we'll be adding our result from the first step (a 2 as a double) to a float. So again, the float gets converted up to a double and we do the addition using doubles.
We now have a value of 3 that is the double type, which we can simply store in our a variable without any conversions at all, since our value is already a double type.
View 4 Replies
View Related
Mar 14, 2014
So, I've used int to float cast before. And it makes sense that it preserves the int value just converts it. I don't really need the answer, I'm just interested, and a resources could suffice.
1. Why in my test program it seems to preserve the int value, I expect that, but why for 0x8000 is it registering bit negation also. I know that is the negative bit for float, but it seems wrong. Is this an error in the gcc compiler conversion code?
2. What is the documentation on these type cast on how they actual work.
3. I know like no assembly, I'm wondering if some of the built in routines to handle or is it all c side code.
4. Can I convert type and preserve the bits. Maybe use void* casting ? I've never really bothered with void* so I don't all that I can do. Except be a pointer that doesn't know the type, obviously. I tested that out in the second code, the output doesn't seem correct, except -0.000. Is it working and my test numbers just are improper float format? It can't be that I test 0x3E20000 = 0.15625 from SingleWiki , but I got 1.328e-36 so the int to void* to float doesn't seem to work in the code below:
#include <cstdio>
int main(){
float flout;
unsigned int num = 1;
int ant;
printf("Int Shift float");
for(unsigned int shift=0;shift<32;shift++){
[Code] ....
View 5 Replies
View Related
Sep 5, 2014
Casting Pointers in C Programming. I don't want to move onto implicit casts until I have this down pat. I'm failing to understand how casting pointers works.
The line
int *mnt = (int*)&flt;
if I read this correctly passes the address of flt which has been converted to an int to the pointer mnt.
1 - When I output mnt I get a garbage value, probably because the address of flt is then converted to a pointer and passed onto mnt as a value and then reinterpreted as a memory address. (that is the first part I don't understand)
2 - - What exactly does the (int*) cast say? Does this mean that a pointer will be returned or an address will be returned. What does the fact that the * is inside the parenthesis mean?
Code:
#include <iostream>
using namespace std;
int main() {
float flt= 6.5;
int *mnt = (int*)&flt;
cout << mnt << endl; // outputs hex memory address
cout << *mnt << endl; // outputs garbage value
}
View 9 Replies
View Related
Apr 13, 2014
This code i made, utilizing the type casting construct, isn't outputting what i wanted. The output for 'Dollars' and 'Cents' are returning '0' for both. instead all i want it to do is seperate the two. for example changing the float value of amount to an integer, giving a dollar value.
Code:
#include <stdio.h>
int main()
{
}
[code]....
View 1 Replies
View Related
Jun 18, 2013
I am doing an exercise which has to do with International country codes.The user must give a code and the programm will display the corresponding country.
Code:
#include <stdio.h>
#define COUNTRY_COUNT
((int) (sizeof(country_codes) / sizeof(country_codes[0])))
[code]....
View 14 Replies
View Related
Dec 2, 2013
I came across some code and it's not clear why it is casting an unsigned char * to another pointer type only to free it right after. Here are the relevant structures:
Code:
struct _Edje_Message {
Edje *edje;
Edje_Queue queue;
Edje_Message_Type type;
int id;
unsigned char *msg;
[Code] .....
As you can see, _Edge_Message has a *msg field, but in the function below, they cast it to the other two structure types inside the case blocks of the switch statement only to free it. What is the point or advantage of doing this?
Code:
void
_edje_message_free(Edje_Message *em) {
if (em->msg) {
int i;
switch (em->type) {
[Code] ......
View 14 Replies
View Related
Aug 19, 2014
I am just getting back in to C++ after 10 years not doing any, contributing to an open source project. I'm adding in some functionality and am hitting a road block.
I need to send a multicast packet out on the network that is structured in a certain way. I have the definition, and know what data is going in each byte. I can successfully send a message using multicast, I now just need to send the right message.
I have used a char array to hold the message, as each char represents 1 byte, and I can transmit the array.
I am having trouble putting all of the data in the right place though. If my source data is a string, then I seem to be able to convert it, but if it is a short or int, then I keep getting errors when compiling. Similarly, two of the lines, (version and type) i initially tried using char arrays with a length of one.
Should I be using memcpy or a different function, or even be doing this in a totally different way altogether? This is the code that I am using, along with the packet structure:
//Construct a Zone Query packet
// 4 bytes - Signature "Ohz " = 0x6f, 0x68, 0x7a, 0x20
// 1 bytes - Version = 1
// 1 bytes - Type (0 = Zone Query, 1 = Zone Uri)
// 2 bytes - Entire message length = 12 + zone length
// 4 bytes - Length in bytes of the zone ID
// n bytes - Zone ID to query
[Code] ....
The errors that I get are:
error: invalid conversion from ‘short int’ to ‘const void*’ [-fpermissive]
memcpy(buffer + 6, packetLength, sizeof(packetLength));
^
[Code] ....
View 9 Replies
View Related
Mar 7, 2012
So I have a vector of 8bit variables. Is it possible to cast that to a vector of 6bit variables like...
8bit: 10011011 01100011 ===>
6bit: 100110 110110 0011XX
View 7 Replies
View Related
Dec 22, 2012
Goal: To allocate some memory as a char*, read in some binary data, re-interpret it as a float* and then free the memory.
My code looks like:
void someFunction(float* &result) {
char * tmp = new char[1000];
//...Fill the char buffer here...
result = (float*)tmp; //Reinterpret binary data as floats
[Code] ....
Is the cast back to char* necessary on the red line (or could I have validly left it as float*)? Would it be different if I had written char * tmp = (char*)malloc(sizeof(char)*1000); on the blue line (and correspondingly used free (char*)floatData on the red line?
View 9 Replies
View Related
May 9, 2014
Debug Error
ProjectsFinal ProjectGrItemDebugGrItem.exe
R6010 - abort() has been called
I was going over this with a friend and it seems as though getline() is not reading anything in and thus throwing the abort error. I'm not sure why this is because I've included the textfile, with the correct name of course, in both the regular file location and the debug folder. I ask for user input and the user then inputs the name of the file they want, I do some required things behind the scenes and display the results for them in a cmd window. I've included pastebin files for both my header and cpp files because it is far to large for one post I shall, however, post the full code in the comments.
Quick Code
The problem occurs on line 159. I'm assuming once this line is fixed, line 163 will have the same problem.
// Read regular price
getline(nameFile, input, '$');
vectorList[count].regPrice = stof(input.c_str());// Casts string to a float
// Read sale price
getline(nameFile, input, '#');
vectorList[count].salePrice = stof(input.c_str());
Pastebin Links : [URL] ....
View 2 Replies
View Related
Jan 4, 2014
I am parsing a binary data file by casting a buffer to a struct. It seems to work really well apart from this one double which is always being accessed two bytes off, despite being in the correct place.
Code:
typedef struct InvoiceRow {
uint INVOICE_NUMBER;
...
double GROSS;
...
char VAT_NUMBER[31];
} InvoiceRow;
If I attempt to print GROSS using printf("%f", row->GROSS) I get 0.0000. However, if I change the type of GROSS to char[8] and then use the following code, I am presented with the correct number...
Code:
typedef struct example {
double d;
}
example;
example *blah = (example*)row->GROSS;
printf("%f", blah->d);
View 7 Replies
View Related
Jun 19, 2013
Is there any way to cast a non-const variable to const one?
I want to read variable n from file and then use it to declare array "int arr[n]", but because n is non-const, the compiler doesn't allow me to do that.
View 6 Replies
View Related