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:
    #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;
    }
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Originally posted by Cheer
    Code:
    	char* string[3];
    You problem is your declaration of string. You declare it as an array of 3 pointers but you never point them at valid data.

    In a real life application you may want to allocate the data for those pointers from the heap, however for now I believe you program would be improved by changing the declaration of string to

    [code=c]
    char string[3][80];
    [/code]

    That is an array of array of chars.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      The basic problem here is that you want to enter three strings but all you have defined is an array of three pointers. Those pointers have to point to memory that holds the string.

      Usually, you have a fixed buffer, say 80, and you fgets into that buffer. Then you can strlen what's in the buffer, malloc the correct memory, copy the buffer to string[j] and then go after the next string.

      Later, you will learn techniques that don't require a fixed 80 for the program to work but, for now, just use a buffer of known size and be sure to keep your data entry within that buffer size.

      Comment

      • Cheer
        New Member
        • Mar 2008
        • 6

        #4
        Thanks a lot, I did it :))) I have never realized that *string[3] is not equal to array string[3][80], and that the first is an array of pointers, and the second is an array of chars, because the type of both is the same (char). thanks very much :)

        Comment

        Working...