Array pointer types of nested types

This is similar to a question that had to be answered already somewhere, but I can not find something satisfactory. In any case, I need to return something similar from the function:

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

I am familiar with using argv , and I understand what its types mean, but for some reason I can't get the type of the above expression correctly. There will always be 2 string literals in the innermost part, and so I thought something like

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

should be what I do, but for some reason I always get segfault no matter what permutation I try when I try to iterate and use printf . Also, the compiler constantly complains about incompatible types of pointers, extra elements and too many braces. This is the current code:

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

You are close.

 #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]); } } } 

The above prints: foo bar baz spam eggs ham

+9
source

It's simple

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

A little explanation:

 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" 
+1
source
 char *s[][2] = { {"foo", "bar"}, {"baz", "spam"}, {"eggs", "ham"} }; cout<<s[1][0]; 

will print baz

0
source

Source: https://habr.com/ru/post/1445434/


All Articles