简体   繁体   中英

strncat implementation?

I'm sorry if this is too entry-level, but I tried implementing the library function of strcpy strncat() as follows:

#include <stdio.h>

void strncat (char *s, char *t, int n) {
// malloc to extend size of s
s = (char*)malloc (strlen(t) + 1);

// add t to the end of s for at most n characters
while (*s != '\0') // move pointer
    s++;

int count = 0;

while (++count <= n)
    *s++ = *t++;

*(++s) = '\0';
}

int main () {
char *t = " Bluish";
char *s = "Red and";

// before concat
printf ("Before concat: %s\n", s);

strncat(s, t, 4);

// after concat
printf ("After concat: %s\n", s);

return 0;
}

It compiles and runs fine...just that it doesn't concatenate at all!

Greatly appreciate any feedback...thanks!

It seems like you redefine s pointer with your malloc, since you've done it, it doesn't points to your first concatenated string.

First of all function return type should be char*

char* strncat (char *s, char *t, int n)

After, I think you should create local char pointer.

char* localString;

use malloc for allocate space with this pointer

localString = malloc (n + strlen(s) + 1); 

and you don't need to make type cast here, cuz malloc do it itself

in fact, you should use your size parameter (n) here, not strlen(t)

and after doing all concatenation operation with this pointer return it

return localString

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM