2015-09-24 191 views
-3

我想從使用數組指針的文件中讀取兩行。但是,我沒有在屏幕上看到任何東西。我嘗試過在線搜索,但無法解決問題。這是我在Mac上使用Netbeans編寫的代碼。打印char指針數組

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); 
} 
+0

個人而言,我會使用一個調試器 –

+2

'char * points [50]; char c;' - >'char points [50] = {0}; int c;' – BLUEPIXY

+0

我試過,沒有使用指針,並工作。不過,我正在學習指針。因此,我必須有指針。 – Sankalps

回答

1
char *points[50]; 

是不是你想要的,這是50個指針數組char

如果你想指針數組來char[50]您需要:

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

還要注意的是fgets是首選從文件中獲得一條線路

#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; 
} 
+0

非常感謝,這工作完美。爲什麼我們使用malloc? – Sankalps

+0

因此,每次我們創建指針時,我們都必須使用malloc在內存中分配它們,因爲它們不指向任何內容。我對麼? – Sankalps

+0

你是對的,請注意,在這種情況下(當你知道手前有多少物品時),你不需要指向'char'的指針數組,'char points [2] [50];'就足夠了。 –