带指针的简单strcat实现

时间:2013-07-09 07:34:23

标签: c pointers strcat

所以我正在练习使用K& R编写带有指针的c代码。对于 strcat 函数的一个问题,我无法找出我的代码有什么问题,根据Visual Studio,在strcat函数之后返回目标字符串不变。任何建议表示赞赏!

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int strcat(char* s, char* t);
int main(void)
{
char *s="hello ", *t="world";
strcat(s,t);
printf("%s",s);
return 0;
}

int strcat(char* s,char* t)
{
int i;
i=strlen(s)+strlen(t);
s=(char*) malloc(i);
while(*s!='\0')
    s++;
while('\0'!=(*s++=*t++))
    ;
return 0;
}

6 个答案:

答案 0 :(得分:1)

1)以这种方式定义字符串

char *s="hello "

表示您定义了一个文字字符串。文字字符串保存到只读存储器中,因此您无法编辑它

您必须将字符串定义为char数组才能编辑它

char s[100] = "hello ";

2)以这种方式定义你的功能

int strcat(char* s,char* t)

您无法将s的地址更改为函数strcat()。因此,将malloc()内存分配到函数中时,在离开函数时不会更改s地址

3)将你的函数strcat改为

int strcat(char** s,char* t)
{
    int i;
    char *u, *v;
    i=strlen(*s)+strlen(t);
    v = *s;
    u=(char*) malloc(i+1);
    while(*v!='\0')
        *u++ = *v++;
    while('\0'!=(*u++=*t++));
    *s = u;
    return 0;
}

你在主要的地方叫它:

char *s="hello ", *t="world";
strcat(&s,t);

答案 1 :(得分:1)

 strcat(char* s, char* t) 

's'按值发送。调用时's'的值被复制到堆栈中,然后调用strcat()。在strcat返回时,修改后的版本将从堆栈中丢弃。所以's'的调用值永远不会改变(并且你创建了内存泄漏)。

Beward,在C中每个存储单元都可以改变,甚至是参数或指令部分;一些变化可能很难理解。

答案 2 :(得分:1)

  1. 我很确定strcat在实际实现中返回char*(保存第一个字符串的原始值)。
  2. strcat不应该改变第一个参数的地址,所以你不应该调用malloc
  3. 第2点意味着您需要在char *s中将char s[20]声明为main(其中20是一个足以容纳整个字符串的任意数字)。
  4. 如果你真的想改变输入参数的值,你需要传递值的地址 - 所以它需要在函数声明/定义中为strcat(char **s, ...),并用{{在strcat(&s, ...)中的1}}。

答案 3 :(得分:0)

由于你试图像真正的strcat一样,它说第一个参数

The string s1 must have sufficient space to hold the result.

所以你不需要使用malloc

char *strcat(char* s, const char* t);
int main(void)
{
  char s[15] = {0}; // 
  char *t = "world";  //const char * so you can't change it

  strcpy(s, "Hello ");
  strcat(s,t);
  printf("%s\n",s);
  return (0);
}

char *strcat(char* s, const char* t)
{
  int i = 0;

  while (s[i] != '\0')
    i++;
  while (*t != '\0')
    s[i++] = *t++;
  s[i] = '\0'; //useless because already initialized with 0
  return (s);
}

答案 4 :(得分:0)

尊敬的用户

你不必太复杂化事情。 strcat的最简单代码,使用指针:

void strcat(char *s, char *t) {
    while(*s++); /*This will point after the '\0' */
    --s; /*So we decrement the pointer to point to '\0' */
    while(*s++ = *t++); /*This will copy the '\0' from *t also */
}

虽然,这不会让你报告串联的成功。

请看这个main()部分以了解答案的其余部分:

int main() {
    char s[60] = "Hello ";
    char *t  = "world!";

    strcat(s, t);
    printf("%s\n", s);

    return 0;
}

s[60]部分非常重要,因为如果它没有足够的空间,你就不能将另一个字符串连接到它。

答案 5 :(得分:-1)

#include<stdio.h>
#include<string.h>
#define LIMIT 100
void strcatt(char*,char*);
main()
{   
int i=0;
char s[LIMIT];
char t[LIMIT];
strcpy(s,"hello");
strcpy(t,"world");
strcatt(s,t);
printf("%s",s);
getch();
}
void strcatt(char *s,char *t)
{   

while(*s!='\0')
{    
 s++;
}
*s=' ';
++s;
while(*t!='\0')
{
    *s=*t;
    s++;
    t++;
}
*s=*t;
}
相关问题