C Programming - Library Functions - Discussion


Point out the error in the following program.


int main()
    char str1[] = "Learn through IndiaBIX\0.com",  str2[120];
    char *p;
    p = (char*) memccpy(str2, str1, 'i', strlen(str1));
    *p = '\0';
    printf("%s", str2);
    return 0;

[A]. Error: in memccpy statement
[B]. Error: invalid pointer conversion
[C]. Error: invalid variable declaration
[D]. No error and prints "Learn through Indi"

Answer: Option D


void *memccpy(void *dest, const void *src, int c, size_t n); : Copies a block of n bytes from src to dest

With memccpy(), the copying stops as soon as either of the following occurs:
=> the character 'i' is first copied into str2
=> n bytes have been copied into str2

Nishitha said: (Aug 20, 2011)  
Why is that a character 'i' is sent as actual parameter when a integer value is being expected in memccpy function?

Nishanthan144 said: (Aug 31, 2011)  
May be the function takes the ASCII value of 'i'.

Arnab said: (Jul 22, 2013)  
Any character is actually a integer in C as we can store.

int ch='a';

Devendra said: (Apr 20, 2014)  
Does *p = '\0' does not make the string str2 empty? As this is having the same address as str2.

Kapil said: (Jul 2, 2014)  
memccpy returns pointer to the end of the string if c is encountered first rather than whole str1 is copied into str2.

Rohan said: (Jun 10, 2018)  
char str1[] = "Learn through IndiaBIX\0.com", str2[120];

Step 1: a string str1[] of characters has been created with following string and a string str2[120] of characters
has been created..

char *p;

Step 2: a pointer p of characters has been created.

p = (char*) memccpy(str2, str1, 'i', strlen(str1));

Step 3: (i) memccpy is a function with
-> str2[destination]
-> str1[source]
-> 'i ' [the condition that the string will copy from str1 to str2 till str2 encounters a character 'i']
-> strlen(str1) [otherwise it copies all the string length of str1 to str2]

*p = '\0';

Step 4: It stores the '\0' character at the end of the p which contains string [" Learn through Indi\0"]\

printf("%s", str2);

Step 5: It will print the string copied from str1 to str2 and prints the string till it encounters '\0'

Suraj said: (Sep 10, 2019)  
Thanks @Rohan.

Soldi said: (Apr 5, 2021)  
Why we are copying 'i' and why not we are printing the printf statement like normal? Please explain me.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.