gpt4 book ai didi

c - 指针数组的问题

转载 作者:行者123 更新时间:2023-12-01 02:31:36 24 4
gpt4 key购买 nike

我有一个入门级 C 指针问题...假设我有两个字符串,我想打印它们。我在下面的代码中误解了什么?

void print_array(char **array[]) {
int i = 0;
while((*array)[i] != NULL) {
printf("%s\n", (*array)[i++]);
}
return;
}

int main(int argc, char** argv) {
char str1[] = "hello";
char str2[] = "world";
char **array = {str1, str2};

print_array(&array);
return (EXIT_SUCCESS);
}

为了让我的代码正常工作,我需要像在 print_array

中一样访问数组

最佳答案

另一种方式(更多的重构)。

错误修正:

  • 纠正了在 print_array 中应该取消引用的内容以及如何取消引用的混淆(不要渴望三星级编程,除非你必须这样做)
  • 将缺失的 sentinel-0 添加到从 main 传递到 print_array 的数组中

其他变化:

  • 删除了多余的 return 语句(main 末尾有一个隐式的 return 0;)
  • 删除了对 0/NULL 的不平等的多余检查
  • print_array 中删除了一层间接寻址
  • 在适当的情况下在 print_array 中使用 const
  • 消除了 print_array 中的反变量
  • main 中使用常量复合文字(需要 C99)
#include <stdio.h>

void print_array(const char *const array[]) {
while(*array)
printf("%s\n", *array++);
}

int main() {
print_array((const char*[]){"hello", "world", 0});
}

See here on coliru


撤消更改 print_array 签名的清理步骤:

#include <stdio.h>

void print_array(char **array[]) {
for(char** p = *array; *p; p++)
printf("%s\n", *p);
}

int main() {
print_array(&(char**){(char*[]){"hello", "world", 0}});
}

Live on coliru

关于c - 指针数组的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25800340/

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