Scanf function changes value of in-loop variable

Justin Whear justin at economicmodeling.com
Wed Apr 16 11:05:29 PDT 2014


On Wed, 16 Apr 2014 17:47:03 +0000, Capture_A_Lag wrote:

> Hi all!
> I have this code:
> 
> 
------------------------------------------------------------------------------
> ubyte N, M, K;
> ubyte[][max][max] Matrix;
> 
> scanf("%d %d %d", &N, &M, &K);
> 
> ubyte tmp;
> 
> for(ubyte n = 1; n <= N; n++)
> 	for(ubyte m = 1; m <= M; m++)
> 	{
> 		scanf("%d", &tmp);
>                  // After this scanf n becomes 0 for no reason
> 		
>                  if(tmp) Matrix[m][tmp] ~= n;
>          }
> 
> 
------------------------------------------------------------------------------
> 
> After scanf in loop variable n becomes 0. Is this a bug? Please help me!

You are using the wrong format spec for an unsigned ubyte; switch out all 
instances of "%d" with "%hhu" and it should work.  Short version: the "%
d" instructs the C scanf function to overwrite 32bits of the stack 
starting at tmp which is only 8 bits long.

Even better than using the proper format spec, you could swap out the non-
typesafe C functions and use the D equivalents readf and formattedRead 
(see std.stdio and std.format).

Justin


More information about the Digitalmars-d-learn mailing list