2015-09-24 193 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];'就足够了。 –