Problem with pointers and string array. C.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Cheer
    New Member
    • Mar 2008
    • 6

    Problem with pointers and string array. C.

    Hello, could anyone help me with C language a little. I'm trying to write a program with pointers, which would scan some words to the array of strings and would print them on a screen. I'm new to C programming, that's why it's so difficult to deal with such a simple task

    [code=c]
    #include <stdio.h>
    #include <string.h>

    int main ()
    {
    char* string[3];
    int j;
    for(j=0;j<3;j++ )
    {

    fgets(string[j], sizeof string[j], stdin);

    }

    for(j=0;j<3;j++ )
    {
    printf("String number %d: \"%s\"\n", j, string[j]);
    }
    return 0;
    } [/code]
  • debasisdas
    Recognized Expert Expert
    • Dec 2006
    • 8119

    #2
    Question moved to C / C++ Forum.

    Comment

    • davidcollins001
      New Member
      • Mar 2008
      • 16

      #3
      Originally posted by Cheer
      Hello, could anyone help me with C language a little. I'm trying to write a program with pointers, which would scan some words to the array of strings and would print them on a screen. I'm new to C programming, that's why it's so difficult to deal with such a simple task
      If you are going to declare a 2D array of strings you need to allocate memory for the string (using malloc) otherwise everytime you read a string with fgets it will be overwritten.

      You cannot tell fgets the length of the string that it will get before it gets it. If you allocate a suitable size string then use the same length with fgets it will read no
      more than that.

      You may want to replace the second last character (\n) too ;)

      [code=c]
      #include <stdio.h>
      #include <string.h>

      int main ()
      {
      char* string[3];
      int j;
      for(j=0;j<3;j++ )
      {
      string[j] = (char *)malloc(BUFSIZ );
      fgets(string[j], sizeof BUFSIZ, stdin);

      }

      for(j=0;j<3;j++ )
      {
      printf("String number %d: \"%s\"\n", j, string[j]);
      }
      return 0;
      } [/code]

      Comment

      Working...