Click here to Skip to main content
15,893,508 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
ok so I have this C++ code:
#include "StdAfx.h"
#include <stdio.h>
#include <cstdlib>

using namespace std;



int main()
{
	 system("PAUSE");
typedef int ty[5];
ty sec[6];
for (int i=0;i<5;i++){
	for(int j=0;j<6;j++){
		sec[i][j]=i*6 +j;
		printf("%d \t",i*6 +j);
	
		printf("%d \n",sec[i][j]);
	}}
int*  p=sec[0];
for(int i=0;i<5;i++){for(int j=0;j<6;j++){printf("%d   %d    %d\n",sec[i][j],i,j);printf("%d\n",*p);
	p++; }}
	

 system("PAUSE");
}
(#include "StdAfx.h" is Visual Studio precompiler header)
what it does is preety obvious !
the problem is that the values printed are not what I expected them to be !
at the first loop everything is ok and sec[i][j] == i*5 +j
at the second one however things get nasty
when using the array ,the last element of every ty is 'missed'
(it prints 0 1 2 3 4 6 6 instead of 0 1 2 3 4 5 6)
when using pointers it gets even worse
can someone explain what I'm doing wrong ?
thanks a lot !!!
Posted

Your array definition doesn't match the for loops. Change from
C++
typedef int ty[5];
ty sec[6];

to
C++
typedef int ty[6];
ty sec[5];

(alternatively you may change the for loop upper limits).
 
Share this answer
 
I am not so sure that this code is want you want
C++
typedef int ty[5];
ty sec[6];


I guess this is want you want - and its more cleaner.
int sec[5][6];
 
Share this answer
 
Comments
Member 10964099 29-Nov-14 14:57pm    
well...yes
I kinda confused rows and columns
but why does sec[i][j] of first loop differ from sec[i][j] of second loop for some values ???
Quote:
C#
sec[i][j]=i*6 +j;

...

at the first loop everything is ok and sec[i][j] == i*5 +j

That comes as a surprise considering the mismatching factor. (I suppose you meant to write ==i*6+j)

If the above solutions didn't help finding the error, I suggest you check out this article on multidimensional arrays[^] which also offers code examples that are a lot more readable than yours (hint, hint! ;-) )
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900