Click here to Skip to main content
15,920,438 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
#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;
    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?
Updated 2-Sep-18 7:59am

1 solution

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. :)
Share this answer
Member 13922884 2-Sep-18 8:21am    

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900