C Programming - Library Functions - Discussion
Discussion Forum : Library Functions - Yes / No Questions (Q.No. 2)
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;
}
Answer: Option
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.
Discussion:
3 comments Page 1 of 1.
Juilee said:
10 years ago
What is garbage value?
Denis said:
10 years ago
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;
}
#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;
}
Kishorkodag said:
1 decade ago
How to assign in garbage value?
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers