-3

I am trying to read two lines from a file using array of pointers. However, I am not getting anything on screen. I have tried searching online, but could not solve the problem. Here is my code that I have written using Netbeans on mac.

int main(int argc, char** argv) {


            FILE *fp;
        char *points[50];
            char c;
        int i=0; 

        fp=fopen("/Users/shubhamsharma/Desktop/data.txt","r");
        if(fp==NULL)
        {
                printf("Reached here");
            fprintf(stderr," Could not open the File!");
            exit(1);
        }
            c=getc(fp);
        while(c!=EOF)
               {
                *points[i]=c;
                c=getc(fp);
                i++;
           } 

        for(int i=0;*points[i]!='\0';i++)
        {
                char d=*points[i];

            printf("%c",d);
                if(*(points[i+1])==',')
                {
                    i=i+1;
                }
        }
    return (EXIT_SUCCESS);
}
Sankalps
  • 23
  • 4

1 Answers1

1
char *points[50];

Is not what you want, this is an array of 50 pointers to char.

If you want an array of pointers to char[50] you need:

char (*points)[50];
points = malloc(sizeof(*points) * 2);

Also note that fgets is prefered to get a line from a file

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    FILE *fp;
    char (*points)[50];

    points = malloc(sizeof(*points) * 2);
    if (points == NULL) {
        perror("malloc");
        exit(EXIT_FAILURE);
    }
    fp = fopen("/Users/shubhamsharma/Desktop/data.txt", "r");
    if (fp == NULL) {
        perror("fopen");
        exit(EXIT_FAILURE);
    }
    fgets(points[0], sizeof(*points), fp);
    fgets(points[1], sizeof(*points), fp);
    fclose(fp);
    printf("%s", points[0]);
    printf("%s", points[1]);
    free(points);
    return 0;
}
David Ranieri
  • 39,972
  • 7
  • 52
  • 94
  • Thanks much, That worked perfectly. why we used malloc though? – Sankalps Sep 24 '15 at 08:17
  • So, everytime we create pointers we have to allocate them in the memory using malloc, as they don't point to anything. Am I correct? – Sankalps Sep 24 '15 at 08:19
  • You're right, note that in this case (when you know how many items before-hand) you don't need an array of pointers to `char`, `char points[2][50];` is enough. – David Ranieri Sep 24 '15 at 08:23