【发布时间】:2021-04-22 05:46:36
【问题描述】:
我正在尝试从 txt 文件中获取一些单词并将它们存储到 char** 中。虽然我认为我的数组为 100 个单词分配了正确的空间,但我的最后一个无法以人类可读的方式打印。另外,如果你仔细看,有 4 个字符正在打印(所以这表明内存的大小是正确的指单词的长度,即4)。你能指出我错过了什么吗?我在 linux Ubuntu 20.04 (VirtualBox) 中运行。
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include <fcntl.h>
#define N 100
#define STRLIM 60
char** cat;
int fd;
int main(int argc, char const *argv[])
{ int i;
cat=(char**)malloc(sizeof(char)*N);
fd=open("dictionary.txt",O_RDONLY);
if(fd==-1){
printf("fd error %d" , fd);
perror("Error:");
}
for(i=0;i<N;i++){
cat[i]=(char*)malloc(sizeof(char)*STRLIM);
read(fd,cat[i],40);
printf("%s", cat[i]);
}
printf("the value of i is: %d",i);
return 0;
}//end of main
PS:我收到如下警告: v1.c:25:9:警告:函数‘read’的隐式声明;您指的是 “fread” 吗? [-Wimplicit-function-declaration]
“read”真的有必要将 unsigned int 作为第三个参数吗?
“dictionary.txt”的单词是这些(下面有一百个单词):
shocking
boundary
post
dapper
zoom
bashful
damaging
sore
unadvised
fresh
birthday
wrathful
hook
nose
wonder
doubt
important
synonymous
bell
dare
selective
raspy
unused
heavy
wiggly
land
coal
humorous
humdrum
plausible
languid
depressed
imminent
helpless
parsimonious
verse
deep
tricky
window
sedate
torpid
earsplitting
protect
breath
drawer
pear
bomb
drum
can
superficial
crook
stimulating
majestic
innocent
steep
robin
weak
tumble
geese
bulb
channel
frantic
obtain
shave
nerve
boiling
picture
sand
measly
tasteful
steadfast
hallowed
rabid
fax
aspiring
utter
wave
confused
zephyr
absent
lamentable
idea
oatmeal
comfortable
cars
reduce
colossal
heat
lettuce
simple
homeless
decision
cellar
ruthless
time
railway
possible
silly
chance
food
【问题讨论】:
-
read(fd,cat[i],40);?您当然不想每次都读取 40 个字节 -
'cat=(char**)malloc(sizeof(char)*N);'为 N 个字符分配空间,而不是 N 个字符*
-
Martin 感谢您告诉我这只是一个错字,但您明白了。此外,正如 BlueDiary 告诉我的那样,我还包括了 unistd.h,而且我还发现“读取”功能很友好灵活且不需要无符号整数作为其第三个参数。非常感谢您的帮助。
-
如果您想使用已经在代码中编写的功能,是否有任何类型的扩展 (VsCode) 可以自动为您填充哪些库?而且,要求可能有点过分,但是首先是什么导致了打印问题?
标签: c parsing char malloc file-descriptor