Marco De Simone Marco De Simone - 1 year ago 125
C Question

conversion string to int with cast in C

i have a string (five characters) and i tried to do an int cast to convert the entire string in a unique value. It worked but i want to know what appens during the conversion. For example

int main(){
char s[6];
int number;

Thank you

Answer Source

The method you seem to be trying to use does not work.

s is an array expression. In most (but not all!) contexts, an array expression is implicitly converted to a pointer to its first element.

So you have:

char s[5];
int number;
number = (int)s;

s, after the implicit conversion, yields a pointer to the first element of the array, equivalent to &s[0]. The cast converts that pointer value to type int, yielding a result that may or may not be at all meaningful (it can lose information if pointers happen to be wider than int on your system).

You say it "works", but it doesn't do at all what you intend. Two different arrays holding the same string value will have distinct addresses, and will probably yield distinct int values when converted.

If you want to track the distinct address of each array object, use pointers, not integers. If, for some reason, you need distinct integer values corresponding to addresses, use the type intptr_t or uintptr_t, defined in <stdint.h> to guarantee that you won't lose information (but it rarely makes sense to do that).

A cast (an explicit conversion) can be thought of as a way to tell the compiler that you know exactly what you're doing, and to override type checking (that's an oversimplification). If you do know what you're doing, that's fine. If you don't, you're likely to shoot yourself in the foot.

You're trying to get unique values corresponding to strings. What is your actual goal? Why can't you use the strings themselves as unique values?

Also, this:


is unsafe. It will read a whitespace-delimited sequence of characters of any arbitrary length from standard input. By defining char s[5], you've only allowed enough room for a 4-character string (plus 1 for the terminating '\0'). If the user types more than that, the extra characters will clobber other memory, with unpredictable results (the technical term is undefined behavior).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download