OK, this is a simple bit of procedural code i am trying to write for achieving the functionality of atoi
function. The thing bothering me is that i am unable to change the dummy
variable in the if
block while i can change the n
variable.The n
and dummy
are defined in the same scope.
int main()
{
char *s;
puts("Enter a string");
fgets(s,100,stdin);
int n = 0 , dummy = 1; // both are defined in the same scope
for(int i = 0 ; i < 2 ; i++ )
{
if(isdigit( s[i] )) { n = n*10 + (s[i] - '0'); }
if(1)
{
dummy = dummy + 99; // This is the thing not working , program stops executing
// n = n + 99; while this works fine
printf("%d\n", dummy );
}
}
printf("%d", n);
}
I can print the dummy
variable fine but i am not able to assign it a value and when i tried to do that program stops working.If i comment the line involving dummy
and uncomment the below line using n
, the program runs fine.
Don't mess with the logic.So what's happening ?
char *s;
s
needs memory to be allocated either statically or dynamically
char s[100];
or
char *s = NULL;
s = malloc(100);
if (s)
/* do operations with s */
.
.
if (s)
free(s);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments