| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 1490 人关注过本帖
标题:[求助]c++ syntax about 2d array
取消只看楼主 加入收藏
HJin
Rank: 6Rank: 6
等 级:贵宾
威 望:27
帖 子:401
专家分:0
注 册:2007-6-9
收藏
 问题点数:0 回复次数:3 
[求助]c++ syntax about 2d array
I wrote a function

// a is 2d --- n x n matrix
void f(int** a, int n); // (1)

int main()
{
const int n=3;
int a[n][n]; // (2)

/**
Question: how do I pass the matrix a to f()?

Don't modify lines (1) and (2).

Thanks.
*/
return 0;
}
搜索更多相关主题的帖子: syntax array 
2007-06-21 14:35
HJin
Rank: 6Rank: 6
等 级:贵宾
威 望:27
帖 子:401
专家分:0
注 册:2007-6-9
收藏
得分:0 

1. 野比's soln does not work, test the program below yourself:

[CODE]#include <iostream>
using namespace std;
void f(int** a, int n)
{
int i;
int j;
for(i=0; i<n; ++i)
for(j=0; j<n; ++j)
a[i][j] = i+j;
}

int main(int argc, char** argv)
{
const int n=3;
int a[n][n];
int* b = &(a[0][0]);
int** c = &b;
f(c, n);
return 0;
}[/CODE]

2. tobyliying --- I just want to understand a C++ syntax.

3. I wrote the function f(), assuming that I will pass a dynamically allocated 2d array to it. Then I changed idea --- I just want to pass a 2d array on the program stack (instead of the heap).

Your suggestion is good --- but I don't know n beforehand. Thus "pointer to array of lenght n" approach is not appropriate.


I am working on a system which has no Chinese input. Please don\'t blame me for typing English.
2007-06-22 02:51
HJin
Rank: 6Rank: 6
等 级:贵宾
威 望:27
帖 子:401
专家分:0
注 册:2007-6-9
收藏
得分:0 
野比's way

[CODE]int* b=&a[0][0]; //a pointer to the start of the array
int** c=&b; //a pointer points to the pointer which points to the array... wow.....tongue twister... (^^!)
//now you can use the c pointer as the parameter of f() instead...[/CODE]

on my system gives access violation error. b points to the start of the 2d array, c is just the address of the b variable, so that

[CODE]c[2][2] = 1;[/CODE]
fails.





I am working on a system which has no Chinese input. Please don\'t blame me for typing English.
2007-06-22 23:38
HJin
Rank: 6Rank: 6
等 级:贵宾
威 望:27
帖 子:401
专家分:0
注 册:2007-6-9
收藏
得分:0 
thanks 野比 and aipb2007, got your guys' idea.

I am working on a system which has no Chinese input. Please don\'t blame me for typing English.
2007-06-25 01:54
快速回复:[求助]c++ syntax about 2d array
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.021536 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved