char name[3]="456";
int i=(int)name;
printf("%i\n");
i need to cast from a char array to an int. in this scenerio, it prints this to the screen
2080313852
can anyone help?
char name[3]="456";
int i=(int)name;
printf("%i\n");
i need to cast from a char array to an int. in this scenerio, it prints this to the screen
2080313852
can anyone help?
You need to use atoi(name). This function is included in stdio.h or stdlib.h, not sure which.
>>> int i = atoi(name);
You can also use atof() to change it to a double.
Also, your print should look like this:
printf("%d", i);
The variable name points to the start of the array. It is a pointer, so when you print name, you print the address of name [0]. In other words, i has the value &name[0].
You cannot cast a string to an int. As drharv pointed out, you could use atoi, or write your own conversion function.
This is incorrect, because the declared dimension of the char-array "name" is too low because the string "456" will be terminated (like all strings in C) by '\0' (usually ASCII 0). In your code the memory after "name" will be overwritten by the terminating '\0'. But the overwritten memory could be important and your system may crash or produce errors.char name[3]="456";
You could write it as
char name={'4', '5', '6'};
but then the compiler canīt find the stringīs end.
The correct version would so be:
Code:char name [4]="456"; or char *name="456";
klausi
Last edited by klausi; 03-06-2002 at 08:59 AM.
When I close my eyes nobody can see me...