Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Int to a char* pointer

Tags:

c

I'm trying to convert an integer to a char* pointer so I can properly send the argument into another function. Is there anyway to do this without atoi?

int number=2123, number2= 1233; 
char* arg[];

arg[0] = number;
arg[1] = number2;

**Sorry for not making things clear so basically I want the arg[0] to equal the string rep of the number, so that i can send it into a function like this: converted(char* arg);

i would change the parameter data type but it has to be that pointer to send in.

like image 245
Eddy Y Avatar asked Feb 20 '26 06:02

Eddy Y


1 Answers

If you assume that a pointer is always at least the same size as an integer (are there any exceptions to this?) you can safely convert integers to pointers and back with these macros:

#define INT2POINTER(a) ((char*)(intptr_t)(a))
#define POINTER2INT(a) ((int)(intptr_t)(a))

Or if that other function isn't your function, but a function that wants the integers as string you could use asprintf() like this:

asprintf(&arg[0],"%d",number);
asprintf(&arg[1],"%d",number2);

But asprintf is not posix standard so it might not be available on all systems. You could use sprintf() (or snprintf() so be on the safe side) instead, but then you need to calculate the string length first.

like image 92
Fabel Avatar answered Feb 21 '26 19:02

Fabel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!