Scanf function changes value of in-loop variable

FreeSlave freeslave93 at gmail.com
Wed Apr 16 11:05:26 PDT 2014


On Wednesday, 16 April 2014 at 17:47:05 UTC, 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!

I suppose it's because scanf wait for int variable (which 4 
bytes), but you pass pointer to ubyte, and when you input data it 
overwrites neighbor bytes.


More information about the Digitalmars-d-learn mailing list