Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ typecast array

How can one typecast an array of int to an array of float? Thanks.

like image 780
Karl Glaser Avatar asked Dec 15 '09 16:12

Karl Glaser


People also ask

Can you typecast an array in C?

In C, you can uses casts to convert between types. That's not called a typecast, however. The C language specification generally frowns upon type punning, where you access an object of one type through a pointer of another type.

Can we typecast array?

you try to cast an Array of Object to cast into Array of Integer. You cant do it. This type of downcast is not permitted. You can make an array of Integer, and after that copy every value of the first array into second array.

How typecast works in C?

Type Casting is basically a process in C in which we change a variable belonging to one data type to another one. In type casting, the compiler automatically changes one data type to another one depending on what we want the program to do.

How do you typecast?

Typecasting is making a variable of one type, such as an int, act like another type, a char, for one single operation. To typecast something, simply put the type of variable you want the actual variable to act as inside parentheses in front of the actual variable. (char)a will make 'a' function as a char.


2 Answers

#include <algorithm>
#include <iostream>

#define N 50

int main() {
    int intArray[N] = { ... };
    float floatArray[N];
    std::copy(intArray, intArray + N, floatArray);
    std::cout
        << std::boolalpha << std::equal(intArray, intArray + N, floatArray)
        << std::endl;
    return 0;
}
like image 112
ephemient Avatar answered Oct 11 '22 20:10

ephemient


If you have an array of ints, what you basically have is a block of N ints stored contiguously in memory. An array of floats, however, would be N floats stored contiguously in memory, i.e. an entirely different sequence of bits in memory. Additionally, floating point values are represented in binary in an entirely different way than integral values. In fact, you can't even be sure that an int is the same size as a float.

So therefore, you either have to cast each int to a float separately as you process the array, or else create an entirely different array by copying the original array.

For example, you could simply convert each int to a float lazily as you process the array:

int array[100];
// ... fill array with some values

for (int i = 0; i < 100; ++i)
{
  float f = array[i]; // implicit conversion here 
  // now do something with this float
}
like image 21
Charles Salvia Avatar answered Oct 11 '22 20:10

Charles Salvia