简体   繁体   中英

How do you store an array of strings in C and print it back?

I am studying 'The C Programming Language' by Brian Kerningham & Dennis Ritchie.

I'm stuck on 1.9 Character Arrays.

I'm trying to allow the user to input multiple lines of text into the CMD that will then be stored in an array of strings parameter for use by another program. Each new line should be stored as a new object in the array. For now all I want to do is print the Array back to the CMD so I can see its working correctly, any ideas what i am doing wrong?

    #include <stdio.h>
 int main(char string[])
 {
    int c, i;
    char * strs[i];
      for (i=0; i<5 && (c!=EOF()) && c!='\n'; i++){
         strs[i] = c;
      }
      for(i=0; i<5; ++i)
         puts(strs[i]);
 }

Your code has quite a number of mistakes in it.

  1. Your main() prototype is wrong, it should be int main(int argc, char *argv[]); or something equivalent. Dropping the initial int argument is not OK.
  2. You're declaring strs as an array of character pointers (without a valid size!), you probably want a full 2D array of chars, like char strs[100][32]; . Limited, but simpler to manage.
  3. You're storing characters, so you need to keep track of which character index is the current one in the current string. strs[i] = c; should be something like strs[i][j++] = c; . Of course you must also respect the maximum length for each string, and terminate the string properly.
  4. You need to step to the next string (increment i ) on newline.

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