C Programming - Library Functions - Discussion

Discussion Forum : Library Functions - Point Out Errors (Q.No. 2)
2.
Point out the error in the following program.
#include<stdio.h>
#include<string.h>

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;
}
Error: in memccpy statement
Error: invalid pointer conversion
Error: invalid variable declaration
No error and prints "Learn through Indi"
Answer: Option
Explanation:

Declaration:
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

Discussion:
8 comments Page 1 of 1.

Rohan said:   7 years ago
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'

Kapil said:   1 decade ago
memccpy returns pointer to the end of the string if c is encountered first rather than whole str1 is copied into str2.

Nishitha said:   1 decade ago
Why is that a character 'i' is sent as actual parameter when a integer value is being expected in memccpy function?

Soldi said:   4 years ago
Why we are copying 'i' and why not we are printing the printf statement like normal? Please explain me.

Devendra said:   1 decade ago
Does *p = '\0' does not make the string str2 empty? As this is having the same address as str2.

Arnab said:   1 decade ago
Any character is actually a integer in C as we can store.

int ch='a';

Nishanthan144 said:   1 decade ago
May be the function takes the ASCII value of 'i'.

Suraj said:   6 years ago
Thanks @Rohan.

Post your comments here:

Your comments will be displayed after verification.