简体   繁体   中英

I can't print char array's elements with for loop

#include <stdio.h>
int main() {
  char usernames[5][10] = {"Lebron","Davis","Schroder","KCP","Gasol"};
  int i = 0;
  for(i=0; i < 20; i++) {
      printf("%s\n",usernames[i][20]);
 }}

Hello guys, I'm new at programming and I study for use for loop with char arrays. You can see my code in top. The output I want to print is;

Lebron
Davis
Schroder
KCP
Gasol

I put my i into char's second dimension, is it not true? Basically, I want to print all the elements in my array, how can I do it? Thanks in advance.

Here you are storing data into 2d array. So, each row will store a sequence of char or a string. like usernames[0] = "Lebron" and so on. So, array length will be 5. But you are trying to print 20 elements. that will give you runtime error.

here is the solution that will work for you.

#include <stdio.h>
int main() {
  char usernames[5][10] = {"Lebron","Davis","Schroder","KCP","Gasol"};
  int i = 0;
  for(i=0; i < 5; i++) {
      printf("%s\n",usernames[i]);
 }
 return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM