打印字符指针数组
Printing array of char pointers
我正在尝试使用指针数组从文件中读取两行。但是,我没有在屏幕上看到任何东西。我曾尝试在线搜索,但无法解决问题。这是我在 mac.
上使用 Netbeans 编写的代码
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]!='[=10=]';i++)
{
char d=*points[i];
printf("%c",d);
if(*(points[i+1])==',')
{
i=i+1;
}
}
return (EXIT_SUCCESS);
}
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;
}
我正在尝试使用指针数组从文件中读取两行。但是,我没有在屏幕上看到任何东西。我曾尝试在线搜索,但无法解决问题。这是我在 mac.
上使用 Netbeans 编写的代码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]!='[=10=]';i++)
{
char d=*points[i];
printf("%c",d);
if(*(points[i+1])==',')
{
i=i+1;
}
}
return (EXIT_SUCCESS);
}
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;
}