gpt4 book ai didi

c - 如何修改传递给函数的二维数组

转载 作者:行者123 更新时间:2023-11-30 16:50:10 25 4
gpt4 key购买 nike

我知道我们能够通过这样的函数来更改字符串

void    c(char *s)                                                                             
{
int i = 0;

while (s[i])
s[i++] = 's';
}



int main()

{
char str[] = "hello";

c(str);
printf("%s\n", str);
return (0);
}

在这种情况下,它将打印“sssss”。

但是如何像修改字符串一样修改二维数组呢?我的意思是不返回数组。

void    c(char **s)                                                                          
{
int i = 0;
int j = 0;

while (s[i])
{
j = 0;
while (s[i][j])
{
s[i][j++] = 's';
}
i++;
}

}

int main()
{
char tab[2][2];
tab[0][0] = 'a';
tab[0][1] = 'b';
tab[1][0] = 'c';
tab[1][1] = 'd';
c(tab);
printf("%c%c\n%c%c", tab[0][0], tab[0][1], tab[1][0], tab[1][1]);
return (0);
}

这是我们如何做到这一点的想法。

我希望我已经说得足够清楚了?

最佳答案

定义应包含长度。以下将是一个很好的阅读: http://www.firmcodes.com/pass-2d-array-parameter-c-2/

void c(char (*s)[length])

#include <stdio.h>
void c(int len, char (*s)[len])
{
int i = 0;
int j = 0;

while (i < len)
{
j = 0;
while (s[i][j])
{
s[i][j++] = 's';
}
i++;
}

}

int main()
{
char tab[2][2];
tab[0][0] = 'a';
tab[0][1] = 'b';
tab[1][0] = 'c';
tab[1][1] = 'd';
c(2, tab);
printf("%c%c\n%c%c", tab[0][0], tab[0][1], tab[1][0], tab[1][1]);
return (0);
}

关于c - 如何修改传递给函数的二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42319919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com