[英]C fscanf read pointer to array of characters
我正在尝试使用fscanf将文件中的行读取到指向字符数组的指针中。 打印时出现分段错误。 我究竟做错了什么? 我应该使用fscanf以外的功能吗?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "stack.h"
#define MAXSTACK 100
#define MAXLENGHT 100
void main(int argc, char * argv[]){
char *filename;
FILE *fp;
char *lines[MAXSTACK];
char * command;
int top = 0;
int numlines = 0;
if(argc < 3){
fprintf(stderr,"error: Not enough arguments provided\n");
exit(1);
}
filename = argv[1];
command = argv[2];
if ( (fp = fopen(filename,"r")) == NULL ){
fprintf(stderr,"error: Cannot open file %s\n",filename);
exit(1);
}
else{
for(int i = 0; i < 3; i++){
fscanf(fp,"%s",lines[i]);
// printf("%s\n",lines[i]);
}
char **ptr2 = lines;
for (int i = 0; i < 2; i++){
printf("%s\n", ptr2[i]);
}
if (strcmp(command,"pop")==0){
//pop(lines);
}else if (strcmp(command,"print_top")==0){
//print_top();
}else if(strcmp(command,"swap_top")==0){
}
}
}
您可能想使用fgets
读取行:
/* Read a single line into a temporary buffer */
char lineBuffer[MAX_LINE_LENGTH];
while (fgets(lineBuffer, sizeof(lineBuffer), fp) != NULL) {
/* Process the read line */
}
读取临时缓冲区中的一行后,可以使用malloc
将读取的字符串深度复制到您在堆上分配的某些内存中(或者您可以仅使用strdup
),然后可以将指向该内存的指针存储到您的lines
数组:
/* Inside the body of the while loop */
/*
* Deep copy current line into the string pointer array.
* strdup = malloc + strcpy
* Note that free is required to release memory!
*/
lines[currLineIndex] = strdup(lineBuffer);
currLineIndex++;
请注意,当您编写如下代码时:
char *lines[MAXSTACK];
您正在堆栈上分配一个MAXSTACK
项目数组,每个项目都是一个char*
指针。 但是然后您必须为这些指针赋予一些有意义的值(例如:从堆中分配一些内存并指向该内存)。
当然,完成后,您必须扫描整个数组并在每个元素指针上调用free
,以避免内存泄漏。
此外,一种良好的编码习惯是在使用数组之前清除数组中的指针,例如:
memset(lines, 0, sizeof(lines));
fscanf("%s", lines[i])
将读取一系列非空白字符(注意,不是整行)到由lines[i]
指向的内存中。 问题是,您没有设置lines[i]
指向任何内存,这就是为什么出现段错误的原因,您要求将字符序列复制到某个未定义的位置。
如果替换了字符指针数组的声明,则char *lines[MAXSTACK];
,声明了字符数组char lines[MAXLENGTH][MAXSTACK]
的数组,则lines[i]
将是MAXLENGTH
字符的数组,其中fscanf("%s", lines[i])
可以复制到没有段错误。
现在的问题仍然存在,如果字符串fscanf尝试读取的长度超过MAXLENGTH
什么? 答案是,将读取的字符超出了可容纳到lines[MAXLENGTH]
数组中的lines[MAXLENGTH]
,您将得到所谓的缓冲区溢出。 为了防止这种情况,可以使用fscanf("%100s", lines[i])
将fscanf
从字符串读取的最大字符数限制为例如100个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.