C Programming Tutorial 51, String Functions pt.2

preview_player
Показать описание

Рекомендации по теме
Комментарии
Автор

These tutorials are so much better than any others! you need more subscribers!

slimjanders
Автор

adam thanks for the illustrations. they definitely help!

jphamzz
Автор

I think the strncpy example has a small flaw; The destination will not end up with a NULL terminator unless it just so happens that the very next byte of memory has a zero in it, which may not be the case. When you go and try to print dest, you may be disappointed to find that you have "weird characters" afterward. char dest[5]; does not imply that it's been initialized to all zeros.

#include <stdio.h>
#include <string.h>

int main(void) {
char *source = "Adam";
char dest[5] =
strncpy(dest, source, 2);
printf("%s\n", dest);

return 0;
}

results in "Ad---"; notice that strncpy didn't automatically add a \0 to the end - one has to be added manually or has to exist already.

bentz
Автор

No, and for a couple reasons. First of all, you can't do strlen of *source. The strlen function takes a char* not a char. When you dereference the source string you're giving strlen a character, which won't work at all. The other issue with the code you posted is all arrays must be allocated with an integer literal. Meaning that you can't allocate an array with a value determined at run-time, so no variables. If you needed to do such a thing then you'd have to use the malloc function.

iTzAdamX
Автор

Great video, but i'm getting something different though. I'm using Visual C++ express, i tried the same thing, tried to copy just Ad, but it is followed by some strange symbol. Is it the compiler? any ideas? Thx.

yusht
Автор

@34inspiration Comments like these make me want to make more tutorials. Thanks :)

iTzAdamX
Автор

Could I just just do:

char *source = "My String!"
char dest[strlen(*source) + 1]

That way, my array will be long enough?

sonickk
Автор

Hi, i wanted to ask you can you insert a character into a word insted of another character...For example...The user types in word Program, and he also inputs the position of the character that he wants to replace and he inputs the character that he wants to replace...Program, 2, x...He inputs that and its gonna come out like this 'Prxgram'...Pls answer...:)

SerbianGuitar
Автор

i printed the same long string with 5 as my array size. it didn't crash or produce any error. now i'm thinking why?! :/

simransingh
visit shbcf.ru