Chinaunix首页 | 论坛 | 博客
  • 博客访问: 36597
  • 博文数量: 17
  • 博客积分: 10
  • 博客等级: 民兵
  • 技术积分: 10
  • 用 户 组: 普通用户
  • 注册时间: 2011-01-27 17:29
个人简介

芝兰生于幽谷,不以无人而不芳

文章分类
文章存档

2017年(17)

我的朋友

分类:

2017-03-10 20:35:26

原文地址:二维数组参数传递 作者:zyd_cu

方法1:形参给出第二维的长度
 

#include <stdio.h>

void func(int n, char str[][5])
{
           int i;
           for (i = 0; i < n; i++)
           {
                   printf("\nstr[%d] = %s\n", i, str[i]);
           }
}

int main()
{
           char str[][5] = {"abc", "def", "ghi"};
           func(3, str);
           return 0;
}

 

方法2:形参声明为指向数组的指针

#include <stdio.h>

void func(int n, char (*str)[5])
{
           int i;
           for (i = 0; i < n; i++)
           {
                   printf("\nstr[%d] = %s\n", i, str[i]);
           }
}

int main()
{
           char str[][5] = {"abc", "def", "ghi"};
           func(3, str);
           return 0;
}

 

方法3:形参声明为指针的指针,实参传递指针数组

#include <stdio.h>

void func(int n, char **str)
{
           int i;
           for (i = 0; i < n; i++)
           {
                   printf("\nstr[%d] = %s\n", i, str[i]);
           }
}

int main()
{
           char *p[3];
           char str[][5] = {"abc", "def", "ghi"};
           p[0] = &str[0][0];
           p[1] = str[1];
           p[2] = str[2];
           func(3, p);
           return 0;
}

 

方法4:形参声明为指向指针的指针,并对参数进行强制转换

#include <stdio.h>

void func(int n, char **str, int m)
{
           int i;
           char (*p)[m] = (char (*)[m])str;
           for (i = 0; i < n; i++)
           {
                   printf("\nstr[%d] = %s\n", i, p[i]);
           }
}

int main()
{
           char str[3][5] = {"abc", "def", "ghi"};
           func(3, (char**)str, 5);
           return 0;
}

阅读(608) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~