如何解决在 C (xv6) 中访问 Char 数组的单个字符的问题
我在 C 中访问字符数组中的每个字符时遇到问题。
我在程序开始时这样声明字符数组:char ddd[512];
作为全局常量。
然后,我使用 acdgeud
将包含一行随机字符(如下所示:int n; n = read(fd,ddd,sizeof(ddd));
)的文件读入字符字符串。 fd
代表文件描述符,值为 1。
例如,我想访问字符字符串的第二个字符,我尝试了 ddd[1]
,因为我会在 C++ 中这样做。但是,它给了我第一个字符之后的所有内容:cdgeud
。
现在,我如何一次只能获取一个字符?希望这很清楚,并提前感谢您的帮助!
更新:刚刚添加了部分代码:
char ddd[512];
void somefunc(int fd) {
char *another = malloc(512*sizeof(ddd));
int n = 0;
while ((n = read(fd,sizeof(ddd))) > 0) {
if ( n < 0 ) break;
for (int i = 0; i < n; ++i) {
/* I'm trying to copy values in ddd to another one by one */
another[i] = ddd[i]; /* This is not working */
}
}
}
解决方法
(编辑新答案)
要逐步执行 for
,您必须在复制值后测试是否有空字符。您也可以在“=”赋值之后有一个单独的休息时间。
for (int i = 0; i < n && (another[i] = ddd[i]); ++i)
为简单起见,可以使用 strncpy
:
strncpy(another,ddd,sizeof another);
为了确保 \0 终止:
while ((n = read(fd,sizeof(ddd) - 1)) > 0) {
ddd[(sizeof ddd)-1) = '\0'; //assure null termination
}
(original)
Per your comment I can only guess rather than answer properly. Here goes some.
char something[2];
char ddd[512];
int n = read(fd,sizeof(ddd));
printf("c=%c\n",ddd[1]); // print one character (c)
printf("s=%s\n",1+ddd ); // print cdgeud,and perhaps more
// (if memset(ddd,sizeof ddd) happened before read things would be better).
char another[sizeof(ddd)];
ddd[1] = another[1]; // copy whatever is in another[1] into d[1]. Unpredictable as I coded it as another[] is not initialized
printf("s=%s\n",something); // unpredictable...
// if something[0] and [1] not '\0' AND ddd follows in memory (not guaranteed at all)
// then could print those followed by contentsof ddd.
The fact that ddd is not guaranteed to be \0 terminated can be the source of accidental overruns. This works without memset().
char something[2];
char ddd[512];
int n = read(fd,something); // unpredictable...
// if something[0] and [1] not '\0' AND ddd follows in memory (not guaranteed at all)
// then could print those followed by contentsof ddd.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。