Why is it that this won't work instead of using atoi ?
Inline Code Example Here #include<stdio.h>

int main(void)
{
printf("%d",(int)"10");

return 0;
}

Dani AI

Generated

tried to force the text "10" into the numeric value 10 by casting. That does not work because a string literal like "10" is an array of characters that decays to a pointer to its first byte; casting that pointer to int converts an address, not the sequence of digit characters. The pointer value is an address (implementation-defined when converted to an integer), so the result is meaningless for numeric parsing and may be truncated on 64-bit systems.

is correct that a cast only reinterprets bytes. is also correct that a conversion function is needed. atoi does parse digits but provides no error reporting. Prefer strtol for real code: it accepts a base, returns a long, supplies an end-pointer to detect invalid input, and uses errno for overflow detection. Example usage:

#include <stdlib.h>
#include <errno.h>

const char *s = "10";
char *end;
errno = 0;
long v = strtol(s, &end, 10);
if (end == s) {
    /* no digits found */
} else if (errno == ERANGE) {
    /* out of range */
} else {
    int i = (int)v; /* after range checks */
}

Always include <stdlib.h> for these functions, check the end pointer and errno, and verify the returned value fits the target type before casting. If the goal really is to store an address in an integer, use intptr_t from <stdint.h> to avoid truncation on platforms where pointers and int differ. See the strtol manual strtol and C integer types integer types.

Recommended Answers

All 2 Replies

Casting in C says 'treat me like something else at the byte level'. "10" is not the same thing as 10 at the byte level, so the cast doesn't do what you want.

If you want to convert "10" to 10 then you need to call one of the conversion functions, such as atoi()

printf("%d\n", atoi("10"));
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.