Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
93 views
in Technique[技术] by (71.8m points)

How to print 2D array in C?

int main() {

  int i;
  int j;
  char mostRecommended[3][50] = {"Star 4", "Time 5", "Wind 3"};

  for(i = 0; i < 50; i++) {
      for(j = 0; j < 3; j++) {
        printf("%s", mostRecommended[i][j]);
      }
    }
  return 0;
}

I'm trying to print this array to the screen such that it looks like this:

Star 4
Time 5
Wind 3

I keep getting an error on the declaration line that says "error: expected expression before ‘{’ token" and on the printf line it says "warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=]" How do I do this?

question from:https://stackoverflow.com/questions/65947812/how-to-print-2d-array-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Well, this is not really a 2D array. It's more easy to consider it as a one dimension array of strings.

int main() {

  int i;
  char mostRecommended[3][50] = {"Star 4", "Time 5", "Wind 3"};

  for(i = 0; i < 3; i++) {
        printf("%s", mostRecommended[i]);
  }

  return 0;
}

Regarding the original code: mostRecommended[i][j] type is char which is a kind of int. Therefore printf("%s" which expect a char * complain that the type is not the expected one.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...