Like Tree2Likes
  • 1 Post By gemera
  • 1 Post By Matticus

Reading a file into an array of pointers

This is a discussion on Reading a file into an array of pointers within the C Programming forums, part of the General Programming Boards category; Does anyone know why when I print out "array[2]" nothing prints? It just prints blank space. My file definitely has ...

  1. #1
    Registered User
    Join Date
    Mar 2012
    Posts
    32

    Reading a file into an array of pointers

    Does anyone know why when I print out "array[2]" nothing prints? It just prints blank space. My file definitely has text in it, but when I try to assign "text" into the array of pointers it won't show any text. I know fgets() appends a newline at the end of the string, not sure if that has anything to do with it, but I've tried printing everything that should be in "array" with a for loop and I get nothing.

    Code:
    #include <stdio.h>
    #define FILEPATH "/home/user/Desktop/text"
    
    
    int main(){
       FILE *myFile = fopen(FILEPATH, "r");
       if(myFile == NULL) return 0;
      
       char text[100];
       char *array[100];
       int idx = 0;
    
    
       while(fgets(text, 100, myFile)){
          array[idx++] = text;
       }
       
       puts(array[2]);
    
    
    }

  2. #2
    Registered User
    Join Date
    Mar 2012
    Location
    the c - side
    Posts
    203
    Code:
    array[idx++] = text;
    You are assigning your pointers to the same address.

    So its not that you will get nothing.

    They will all point to the last line entered from your file.

    If that is a blank line there will appear to be nothing at all.

    Salem likes this.

  3. #3
    Registered User
    Join Date
    Jun 2011
    Posts
    2,048
    You need to allocate (and eventually free) memory for each pointer in "array" before assigning a string to it. And in 'C', you cannot copy strings with the assignment operator. You need to use "strcpy()".
    Salem likes this.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Parsing a csv file crashing reading array of pointers
    By slackwarefan in forum C Programming
    Replies: 2
    Last Post: 07-23-2010, 01:23 AM
  2. Reading from file into Array
    By lvl99 in forum C Programming
    Replies: 8
    Last Post: 09-23-2009, 02:27 PM
  3. Reading from a file into an array
    By fmsguy06 in forum C Programming
    Replies: 6
    Last Post: 10-18-2008, 09:25 PM
  4. Replies: 1
    Last Post: 04-25-2006, 12:14 AM
  5. Reading file into a 2d array
    By beginner999 in forum C Programming
    Replies: 7
    Last Post: 01-08-2003, 07:19 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21