3

这似乎是一个应该已经在某个地方回答的问题,但我似乎找不到令人满意的东西。无论如何,我需要从一个看起来像这样的函数返回:

{ {"foo", "bar"}, {"baz", "foo"}, {"foo", "bar"} }

我熟悉 of 的使用argv并且理解它的类型的含义,但由于某种原因,我无法正确获取上述表达式的类型。最里面总会有 2 个字符串文字,因此我想像

char **s[2] or char *(*s[2])

应该是我所追求的,但由于某种原因,无论我尝试迭代和使用printf. 此外,编译器不断抱怨指针类型不兼容、元素过​​多和大括号过多。这是当前代码:

 char *(*s[2]) = { {"foo", "bar"}, {"baz", "spam"}, {"eggs", "ham"} };
4

3 回答 3

8

你很亲密。

#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

于 2012-11-12T05:42:12.117 回答
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"
于 2012-11-12T05:41:48.690 回答
0
char *s[][2] = { {"foo", "bar"}, {"baz", "spam"}, {"eggs", "ham"} };


cout<<s[1][0];

会打印baz

于 2012-11-12T05:39:33.620 回答