为什么我在输出中得到垃圾值以及结果? [英] Why am I getting garbage value in the output along with the result?

查看:81
本文介绍了为什么我在输出中得到垃圾值以及结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  #include   <   stdio.h  >  
void fun( char s1 []);
#define size 10
int main()
{
char s1 [size] = feb ;
fun(s1);
return 0 ;
}
void fun( char s1 [])
{
char s2 [size];
int i = 0 ;
while (* s1!= ' \\ \\ 0'
{
s2 [i] = * s1;
s1 ++;
i ++;
}
printf( \ n%s,s2);
}





我的尝试:



以上代码只是一个例子。我想比较函数中的两个字符串。因此我将字符串传递给另一个字符变量。但它会导致垃圾价值和结果。为什么在这里添加了垃圾值?

解决方案

在你的函数 fun()中,你将所有内容复制到终止'\ 0'字符,但不要复制'\0'。这意味着字符串's2'未被终止。



存在标准函数 - strcpy(),在中定义< string.h> - 复制包含终止'\0'字符的字符串。你应该尽可能使用库函数,除非你有非常的理由。像这样的错误是一个原因。 :)

#include <stdio.h>
void fun (char s1[]);
#define size 10
int main() 
{
     char s1 [size]="feb";
     fun (s1);
     return 0;
}
void fun (char s1[])
{
    char s2[size];
    int i=0;
    while (*s1 !='\0')
    {
        s2 [i]=*s1;
        s1++;
        i++;
    }
    printf ("\n%s",s2);
}



What I have tried:

Above code is just an example. I wanted to compare two strings in the function. Hence i am passing the string to another character variable. But it is resulting into garbage value along with the result. Why garbage values have been added here?

解决方案

In your function fun(), you are copying everything up to the terminating '\0' character, but do not copy the '\0'. This means that the string 's2' is un-terminated.

A standard function exists - strcpy(), defined in <string.h> - that copies a string including the terminating '\0' character. You should use library functions where possible, unless you have a very good reason for doing otherwise. Mistakes like this one are one reason. :)


这篇关于为什么我在输出中得到垃圾值以及结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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