Sijith
Sijith

Reputation: 3932

character array filling

I want to declare character array and later want to fill it. But getting error:

char line[BUFSIZE+1];
strcpy(line,"Memory is Full", sizeof(line));

Error is:

wrong number of arguments in call to strcpy. 

Is there any alternative to achive this?

Upvotes: 0

Views: 11598

Answers (3)

unwind
unwind

Reputation: 399979

If you have it, use strlcpy(). It does what you might expect strncpy() to do.

Failing that, I would recommend using snprintf(), if you have it.

Upvotes: 3

Mike
Mike

Reputation: 49463

strcpy() takes 2 arguments, strncpy() takes 3.

I think you were thinking about using strncpy, that takes destination, source, and size.

ie:

int main()
{
    char i[6];
    strncpy(i, "Hello", sizeof(i));
    printf("%s\n", i);    
    return 0;
}

>> ./a.out
>> Hello

Note: You have to append the '\0' yourself if you completly fill your char[], otherwise strncpy() will do it for you (as in my example).

Upvotes: 2

Fred Foo
Fred Foo

Reputation: 363747

strcpy doesn't take a size/length argument. Use memcpy instead, but give it the size (length+1) of the string being copied, not the size of the buffer, or you risk undefined behavior/segfaults.

Upvotes: 1

Related Questions