Numerical value of a string

Pages: 12
it worked if I declare the string as array of characters but not when declared as string....that should suffice for now.

Thank you for all of your inputs.
closed account (Dy7SLyTq)
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv[])
{
	char MyInt = 0;
	
	printf("enter a number: ");
	scanf("%c", &MyInt);
	
	printf("You wrote: %d", atoi(&MyInt));
	return 1;
}
@DTSCode


You are advising to use code with undefined behaviour. &MyInt is not a pointer to a string (there is no terminating zero). So you can get any result.
closed account (Dy7SLyTq)
i just did it five times and it did was i supposed to. i know its not a pointer to a string. it takes a char * so it * points to the & of my char. its not undefined
It is simply fortune that in this simple program your variable are followed by a memory cell with zero. Nevertheless your code has undefined behaviour, Simply speaking it is a bad code.
It reminds me of this thread:
http://www.cplusplus.com/forum/beginner/105264/
*** So I'm right!!!!!!! ***
CharToInt for the win!
Last edited on
Topic archived. No new replies allowed.
Pages: 12