[英]How to pass an array of strings to a function?
有人可以告诉我为什么两个打印的输出不一样吗? 那么如何将字符串数组传递给函数呢?
main()
{
char b[10][10];
printf("%p, %p, %p\n", b, b[0], b[9]);
getStrListFromString(b);
}
void getStrListFromString(char **strList)
{
printf("%p, %p, %p\n", strList, strList[0], strList[9]);
}
预期输出:
0x7fffbe4ecf00, 0x7fffbe4ecf00, 0x7fffbe4ecf5a
0x7fffbe4ecf00, 0x7fffbe4ecf00, 0x7fffbe4ecf5a
实际输出:
0x7fffbe4ecf00, 0x7fffbe4ecf00, 0x7fffbe4ecf5a
0x7fffbe4ecf00, 0x7fffbe4ecf80, (nil)
您的函数需要一个char **
但您要向其传递一个char [10][10]
。 这些不一样。
数组在传递给函数时会衰减为指向第一个元素的指针。 因此,当你传递char [10][10]
的大小10的阵列char [10]
到功能)它衰变为一个char (*)[10]
一个指向char [10]
更改函数以接受char [10][10]
或char (*)[10]
。
除了与多维数组绝对无关的指针对指针的核心问题外,您还遇到其他各种错误:
main() // obsolete form of main(), won't compile unless C90
{
char b[10][10]; // uninitialized
printf("%p, %p, %p\n", b, b[0], b[9]); // should be void pointers
getStrListFromString(b); // wrong type of parameter
// return statement necessary here in C90
}
void getStrListFromString(char **strList) // should not be pointer-to-pointer
{
printf("%p, %p, %p\n", strList, strList[0], strList[9]); // same issue as in main
}
编译该代码的事实意味着您的编译器要么完全废弃,要么配置不正确。 您需要尽快修复该问题。
更正的代码:
#include <stdio.h>
void getStrListFromString(char strList[10][10])
{
printf("%p, %p, %p\n", (void*)strList, (void*)strList[0], (void*)strList[9]);
}
int main (void)
{
char b[10][10];
printf("%p, %p, %p\n", (void*)b, (void*)b[0], (void*)b[9]);
getStrListFromString(b);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.