Question:
C++ casting type question?
Fred
2011-04-18 04:34:06 UTC
Hi, I've got this question about casting; well, I think that'd would come under casting.

So basically, I have a char pointer to a number.
e.g. char *num = '12345'

Now, I want to pass num (the adress of num[0]) to a function, except that I want it to be recognised as an int and I want to use pass by reference.

e.g.

void somefunc (int &number)
{
// Do stuff.
}

int main()
{
char *num = '12345';
somefunc (*num)
}

Basically, I reckon that there should be a way to point to an adress, and interpret what is at the location pointed to, as an integer.

Anyone know if, and how this can be done?

Thanks.

PS Is the way to do this simply using a void pointer?
Four answers:
Cubbi
2011-04-18 06:25:49 UTC
First of all, your program contains a syntax error: only one character can be placed between single quotes.



Depending on what you wanted to write, you need to change

     char *num = '12345';

to either

     const char *num = "12345";

or

     char num[5] = {'\x1', '\x2', '\x3', '\x4', '\x5'};



There are many ways to convert a string to a number (std::stoi() and boost::lexical_cast() are the most convenient), and there is a keyword that lets you "point to an address, and interpret what is at the location pointed to, as an integer", which is called reinrepret_cast.



What is your desired result?
cosimo
2011-04-18 04:53:59 UTC
Your question is not clear to me. Can you try explaining again what you are trying to do? What do you want to be recognised as an int? The pointer to num or the value contained in num? If it's the value contained in num, do you expect it to be interpreted as an integer with value 12345? If so, that's not going to happen. You need to find another way to convert from a character string to an integer, e.g. using sscanf(), itoa() or something.
2016-11-19 01:00:35 UTC
in case you attempt to apply archives defined as one form as yet another form (say an int as a char), the compiler won't enable it. in case you solid an int to a char, the compiler is satisfied. you could fairly in simple terms solid archives of a similar length (casting archives of distinctive lengths can bring about problems). so which you will no longer solid a protracted as an int, or a string as a protracted.
?
2011-04-18 04:42:42 UTC
Did you come across with generic address, void *


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...