Convert char * to int after using strdup ()

Why after using strdup(value) (int)value returns a different result than before? How to get the same result?

My short example went wrong, use the long one: Here is the full code for the tests:

 #include <stdio.h> #include <iostream> int main() { //The First Part char *c = "ARD-642564"; char *ca = "ARD-642564"; std::cout << c << std::endl; std::cout << ca << std::endl; //c and ca are equal std::cout << (int)c << std::endl; std::cout << (int)ca << std::endl; //The Second Part c = strdup("ARD-642564"); ca = strdup("ARD-642564"); std::cout << c << std::endl; std::cout << ca << std::endl; //c and ca are NOT equal Why? std::cout << (int)c << std::endl; std::cout << (int)ca << std::endl; int x; std::cin >> x; } 
+4
source share
2 answers

Since the array breaks up into a pointer in your case, you print the pointer (that is, on non-exotic computers, the memory address). There is no guarantee that the pointer matches int .

  • In the first part of the code, c and ca need not be equal. Your compiler does some memory optimization (see here for a complete answer).

  • In the second part, strdup dynamically selects a string twice, so the returned pointers are not equal. The compiler does not optimize these calls because it does not seem to control the definition of strdup .

In both cases, c and ca may not be equal.

+7
source

"The strdup () function returns a pointer to a new line , which is a duplicate of the line pointed to by s1." a source

So it’s quite clear that the pointers are different.

+4
source

All Articles