这似乎是一个本来应该已经回答的问题,但我似乎找不到令人满意的东西。无论如何,我需要从函数返回看起来像:
{ {"foo", "bar"}, {"baz", "foo"}, {"foo", "bar"} }
我熟悉argv
的使用,我理解它的类型意味着什么,但由于某种原因,我无法得到上述表达式的类型。在最里面的部分总会有2个字符串文字,因此我认为像
char **s[2] or char *(*s[2])
应该是我所追求的但是由于某种原因,无论我在尝试迭代并使用printf
时尝试的排列,我总是最终得到段错误。此外,编译器经常抱怨不兼容的指针类型,多余的元素和太多的大括号。这是当前的代码:
char *(*s[2]) = { {"foo", "bar"}, {"baz", "spam"}, {"eggs", "ham"} };
答案 0 :(得分:9)
你很亲密。
#include <stdio.h>
int main()
{
char* s[][2] = { {"foo", "bar"}, {"baz", "spam"}, {"eggs", "ham"} };
for( int i = 0; i < 3; i++ )
{
for(int j = 0; j < 2; j ++)
{
printf("%s ",s[i][j]);
}
}
}
以上版画:foo bar baz spam eggs ham
答案 1 :(得分:1)
很简单
char *s[3][2] ={ {"foo", "bar"}, {"baz", "spam"}, {"eggs", "ham"} };
一点解释:
char *s ; // |s| ---> "Only one char array or string"
______
char *s[] ; // |s| ---> |_s[0]_|--> 1st pointer to char array --> "1st string"
|_s[1]_|--> 2nd pointer to char array --> "2nd string"
|_s[2]_|--> 3rd pointer to char array --> "3rd string"
___ __
char *s[][] ;// |s| ---> |___|--> 1st pointer to pointer -->|__|-->"1st string"
|__|-->"2nd string"
____ __
|___|--> 2nd pointer to pointer -->|__|-->"1st string"
|__|-->"2nd string"
____ __
|___|--> 3rd pointer to pointer -->|__|-->"1st string"
|__|-->"2nd string"
答案 2 :(得分:0)
char *s[][2] = { {"foo", "bar"}, {"baz", "spam"}, {"eggs", "ham"} };
cout<<s[1][0];
会打印baz