Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strncpy adding extra characters to my char array

Tags:

c++

arrays

I have a character array of words. Some of them surrounded by *. If one is found, I want it put into my buffer array. I looked at test[i] + 1 in my watch window, and it does what I want. It reads as "example*". I figured if I used strncpy to copy this over with two less characters than the size of it, I would get "example", but instead, I'm getting things like "examples." or "examplers.", which doesn't make any sense to me.

char ** test;
char * buffer;
int elemLen;
if (*test[i] == '*')
{
    elemLen = strlen(test[i]);
    strncpy(buffer, test[i] + 1, elemLen - 2);
}
like image 334
Michael Blake Avatar asked Oct 17 '25 16:10

Michael Blake


1 Answers

You must manually add a null character as strncopy will not do it for you.

i.e.

elemLen = strlen(test[i]);
strncpy(buffer, test[i] + 1, elemLen - 2);
buffer[elemLen - 2] = '\0';
like image 109
Austinh100 Avatar answered Oct 20 '25 06:10

Austinh100



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!