C程序打印奇怪的字符 [英] C program printing weird characters

查看:12
本文介绍了C程序打印奇怪的字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序可以读取文件的内容并将其保存到 buf 中.阅读内容后,它应该将两个两个字符复制到一个数组中.如果我不尝试从文件中读取,则此代码可以正常工作,但是如果我尝试从文件中读取它,则缓冲区中的 printf 会打印我想要的两个字符,但会添加奇怪的字符.我已经确认并且它正确保存到 buf 中,那里没有奇怪的字符.我不知道出了什么问题...这是代码:

I have a program that reads the content of a file and saves it into buf. After reading the content it is supposed to copy two by two chars to an array. This code works fine if I'm not trying to read from a file but if I try to read it from a file the printf from buffer prints the two chars that I want but adds weird characters. I've confirmed and it's saving correctly into buf, no weird characters there. I can't figure out what's wrong... Here's the code:

char *buffer = (char*)malloc(2*sizeof(char));
char *dst = buffer;
char *src = buf;
char *end = buf + strlen(buf);
char *baby = '';
while (src<= end)
{
    strncpy(dst, src, 2);
    src+= 2;
    printf("%s
", buffer);
}

推荐答案

  1. (char*)malloc(2*sizeof(char)); 改为 malloc(3*sizeof*buffer); 你需要一个额外的字节存储用于指示 end-of-string 的终止空字符.另外,不要强制转换 malloc() 的返回值.感谢放松

  1. (char*)malloc(2*sizeof(char)); change to malloc(3*sizeof*buffer); You need an additional byte to store the terminating null character which is used to indicate the end-of-string. Aslo, do not cast the return value of malloc(). Thanks to unwind

在您的情况下,使用 strncpy(),您提供了 n 作为 2,它没有任何范围存储终止的空字节.如果没有终止 null,printf() 将不知道在哪里停止.现在,有了 3 个字节的内存,您可以使用 strcpy() 正确复制字符串

In your case, with strncpy(), you have supplied n as 2, which is not having any scope to store the terminating null byte. without the trminating null, printf() won't be knowing where to stop. Now, with 3 bytes of memory, you can use strcpy() to copy the string properly

strncpy()添加终止 null 本身,以防 n 等于提供的缓冲区的大小,从而成为非常非常不可靠(不像 strcpy()).您需要以编程方式处理它.

strncpy() will not add the terminating null itself, in case the n is equal to the size of supplied buffer, thus becoming very very unreliable (unlike strcpy()). You need to take care of it programmatically.

查看 strncpy()strcpy 的手册页() 在这里.

check the man page for strncpy() and strcpy() here.

这篇关于C程序打印奇怪的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆