将字符数组传递给指针并连接字符串

问题描述 投票:0回答:1

当函数内部打印'c'时,我得到两个字符串的串联。但是当返回指针的地址并且在main中打印“i”时,输出不正确。

#include <stdio.h>

char* comp(char* s,char* t)
{
int count=0;
char *c;
c=s;
while(*s!='\0')
    s++;
for(;*t!='\0';t++,s++)
     *s=*t;
return c;
}

int main(){
char* i;
char c[]= "hello there";
char f[]="world";
i=comp(&c,&f);
printf("%s",i);
return 0;
}
c pointers
1个回答
3
投票

我看到的问题:

问题1

你不是null终止comp中的连接字符串。

char* comp(char* s,char* t)
{
   int count=0;
   char *c;
   c=s;
   while(*s!='\0')
      s++;
   for(;*t!='\0';t++,s++)
      *s=*t;

   // Need this
   *s = '\0';
   return c;
}

问题2

您正在调用该函数。你需要使用:

i=comp(c, f); // Not comp(&c, &f)

问题3

最严重的问题是你正在写你不应该写的内存:

当你使用:

char c[]= "hello there";
char f[]="world";

c有足够的记忆来保持字符串"hello there"f有足够的记忆来保持字符串"world"。试图超出这些限制而导致未定义的行为。你可以使用:

char c[100]= "hello there";
char f[]="world";
i = comp(c, f);

这样就行了,因为c有足够的空间来保存连接的字符串。

更新,以回应OP的评论

char c[]= "hello there";

相当于:

char c[12] = {'h', 'e', 'l', 'l', 'o', ' ', 't', 'h', 'e', 'r', 'e', '\0'};

"world"附加到该等效于执行以下操作:

c[11] = 'w';
c[12] = 'o';
c[13] = 'r';
c[14] = 'l';
c[15] = 'd';
c[16] = '\0';

这是导致未定义行为的原因,因为您使用越界索引编写数组的元素。甚至使用越界索引访问数组的元素也是定义行为的原因。

© www.soinside.com 2019 - 2024. All rights reserved.