嵌套数组。指针出错了 [英] nested arrays. Pointers gone wrong

查看:97
本文介绍了嵌套数组。指针出错了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好,所以我有这个C ++代码:

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");
}

(#includeStdAfx.h是Visual Studio预编译器标题)

它的作用是显而易见的!

问题是打印的值不是我预期的值!

在第一个循环中一切正常并且sec [i] [j] == i * 5 + j

在第二个然而事情变得讨厌

使用阵列时,每个ty的最后一个元素是'错过'

(它打印0 1 2 3 4 6 6而不是0 1 2 3 4 5 6)

当使用指针时它变得更糟

有人可以解释我做错了吗?

非常感谢!!!

(#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 !!!

推荐答案

您的数组定义与循环的不匹配。更改

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



to


to

typedef int ty[6];
ty sec[5];



(或者您可以更改 for loop upper limits)。


(alternatively you may change the for loop upper limits).


我不确定这段代码是否需要
I am not so sure that this code is want you want
typedef int ty[5];
ty sec[6];





我猜这个想要你想要它 - 它更清洁。



I guess this is want you want - and its more cleaner.

int sec[5][6];


Quote:

sec[i][j]=i*6 +j;



...


第一个循环的
一切正常,秒[i] [j] == i * 5 + j


...

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



考虑到不匹配因素,这令人惊讶。 (我想你打算写 == i * 6 + 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! ;-) )


这篇关于嵌套数组。指针出错了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆