首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >char**:正确解析整个内存

char**:正确解析整个内存
EN

Stack Overflow用户
提问于 2021-01-18 04:59:13
回答 1查看 60关注 0票数 0

我正在尝试从txt文件中获取一些单词,并将它们存储到一个char**中。尽管我认为我的数组正确地分配了100个单词的空间,但我的最后一个数组无法以人类可读的way.Also格式打印,如果您仔细观察,会发现打印的是4个字符(所以这表明正确的内存大小是指单词的长度,即4)。你能指出我遗漏了什么吗?我在linux Ubuntu20.04 (VirtualBox)上运行。

代码语言:javascript
复制
#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 -声明

"read“真的有必要有一个无符号的int作为第三个论据吗?

"dictionary.txt“的单词是这样的(下面有一百个单词):

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

发布于 2021-01-18 06:02:28

抱歉,无法添加评论...如果包含unistd.h,您将不会收到警告。我不知道您为什么要在这段代码中使用malloc函数(可能用于代码的另一部分)。最好是有一个缓冲区,然后这样做:

代码语言:javascript
复制
char buffer[STRLIM];
int x;
while ((x = read(fd, buffer, STRLIM)) > 0) {
    write(1, buffer, x);
}

其中x是read函数能够从文件中读取的字节数,然后我们将x字节写入输出。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65765880

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档