• Uncategorized

About c++ : How-can-i-get-the-first-element-from-an-array-of-character-containing-float-values

Question Detail

I am trying to get the first element value from array of character containing float.
The character array size is 7, and it’s containing two float elements hence size can be assumed 8. I want to get only the first element ignoring anything about 2nd value.
Here is my code-

int main()
{
 char cArr[7] = {2.0085,4.52};
 char* charPtr = nullptr;

 charPtr=cArr;
 cout<<"char[0] :"<<*charPtr<<endl;
 float* fPtr =(float*)charPtr; 
 cout<<"char[0] :"<<*fPtr<<endl;
 cout<<endl;
}

Here is my output:

g++ b.cpp -o b.exe -std=c++0x
b.cpp: In function 'int main()':
b.cpp:6:29: warning: narrowing conversion of '2.0085000000000002e+0' from 'double' to 'char' inside { } [-Wnarrowing]
  char cArr[7] = {2.0085,4.52};
                             ^
b.cpp:6:29: warning: narrowing conversion of '4.5199999999999996e+0' from 'double' to 'char' inside { } [-Wnarrowing]

./b.exe 
char[0] :
char[0] :1.43773e-42

I am expecting:

char[0] :2.0085

Any suggestions with the code change?

Question Answer

It seems like what you are trying to make your array hold this:

float fArr[2] = { 2.0085, 4.52 };
char cArr[7];
memcpy(cArr, fArr, 7);

The code you gave does not give you access to the bytes of a float’s representation. memcpy will.

However, it’s still not allowed to read a float out of the char array through pointer casting. That is a violation of strict aliasing, and results in undefined behavior. To read four bytes from the array and treat them as the representation of a float, you need a second call to memcpy.

Any suggestions with the code change?

You actually want this:

float cArr[2] = { 2.0085, 4.52 };
float *fPtr = cArr;

If I understand your question correct, you have a text string with comma separated decimal point values. Like: “2.0085,4.52”

Now you want to extract the first decimal point value (i.e. “2.0085”) and convert it to a float (i.e. like float f = 2.0085).

There are two major problems with your code:

1) The text string initialization is wrong and the char array is too short.

2) You can’t do the conversion by casting pointers. You need to call special function that does the conversion (e.g. atof).

One way to do it is like this:

#include <iostream>
#include <cstring>

int main()
{
  // Initialize text string with comma seperated decimal point values
  char cArr[32] = "2.0085,4.52";

  // Extract the first decimal point text string
  char* p = std::strtok(cArr, ",");
  std::cout << "First text string: " << p << std::endl;

  // Convert the text representation to a float representation
  float f = std::atof(p);
  std::cout << "First float value: " << f << std::endl;

  return 0;
}

Output:

First text string: 2.0085
First float value: 2.0085

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.