Mongow
Mongow

Reputation: 69

Why is the last char being cut from the string?

Why is the last char being cut from the string below?

char *data[10];
char napis[] = "Witam";

data[0] = (char*) malloc (sizeof(char) * strlen(napis+1));

strncpy(data[0], napis, strlen(napis+1));
data[0][strlen(napis+1)] = '\0';

printf("%s\n", data[0]);

It seems that everything should be OK, but the program returns one character less (last).

Return "Wita" instead "Witam".

Upvotes: 0

Views: 86

Answers (1)

phschoen
phschoen

Reputation: 2081

By strlen(napis+1) you do a pointer increment so you calculating the length of the chararray 'itam\0'.

To add 1 to the length of the char it would be correct to execute strlen(napis)+1.

char *data[10];
char napis[] = "Witam";

data[0] = (char*) malloc (sizeof(char) * (strlen(napis)+1));

strncpy(data[0], napis, strlen(napis)+1);
data[strlen(napis)+1] = '\0';

printf("%s\n", data[0]);

Upvotes: 2

Related Questions