C Programming - Library Functions - Discussion

2. 

Will the program outputs "IndiaBIX.com"?

#include<stdio.h>
#include<string.h>

int main()
{
    char str1[] = "IndiaBIX.com";
    char str2[20];
    strncpy(str2, str1, 8);
    printf("%s", str2);
    return 0;
}

[A]. Yes
[B]. No

Answer: Option B

Explanation:

No. It will print something like 'IndiaBIX(some garbage values here)' .

Because after copying the first 8 characters of source string into target string strncpy() doesn't terminate the target string with a '\0'. So it may print some garbage values along with IndiaBIX.


Kishorkodag said: (Jul 23, 2011)  
How to assign in garbage value?

Denis said: (Jun 19, 2015)  
Working code:

#include<stdio.h>
#include<string.h>

int main()
{
char str1[] = "IndiaBIX.com";
char str2[20];
strncpy(str2, str1, 8);
str2[8]='\0';
printf("%s", str2);
return 0;
}

Juilee said: (Sep 1, 2015)  
What is garbage value?

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.