简体   繁体   English

用C中的数组构造我自己的strcat函数

[英]construct my own strcat function with arrays in c

I am trying to write a function that works like strcat, I dont get any error when compiling the code. 我正在尝试编写一个类似于strcat的函数,编译代码时没有出现任何错误。 the problem is when calling the function it didnt append the elements in the second array to the first one. 问题是在调用函数时,它没有将第二个数组中的元素附加到第一个数组中。 when I print the first array it still the same. 当我打印第一个数组时,它仍然相同。 any suggesting? 有什么建议吗?

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

char *strcat1(char *dest, char *src);

char *strcat1(char *dest, char *src) {
    int i;
    int j;
    printf("i0=%d, j0=%d\n", i, j);

    i = strlen(dest);
    j = strlen(src);
    for (int z = 0; z < j; z++) {
        dest[z + i + 1] = src[z];    
    }
}

int main() {
    char str1[100];
    char str2[30];
    printf("put the first string:\n");
    fgets(str1, sizeof(str1), stdin);
    printf("\ninput the second string\n");
    fgets(str2, sizeof(str2), stdin);
    strcat1(str1, str2);
    printf("%s", str1);
}

str1 is finished by a '\\0'. str1以'\\ 0'结尾。

strlen returns length of string not including the terminating null character. strlen返回不包括终止空字符的字符串长度。

So for example if string is "toto" then strlen(string) is 4. 因此,例如,如果string为“ toto”,则strlen(string)为4。

In memory : 在记忆中 :

string[0] = 't'
string[1] = 'o'
string[2] = 't'
string[3] = 'o'
string[4] = '\0'

But you are writing at dest[z+i+1] so in my example. 但是您在dest [z + i + 1]上进行写作,因此在我的示例中。 string[z + 4 + 1] whitch is string[5]. 字符串[z + 4 +1]是字符串[5]。 So after the '\\0'. 因此,在'\\ 0'之后。

The result will be : "toto\\0string2". 结果将是:“ toto \\ 0string2”。

But because printf %s stop reading pointer at \\0, you only see "toto". 但是由于printf%s停止读取\\ 0处的指针,因此只能看到“ toto”。

Try to replace 尝试更换

dest[z+i+1]

by 通过

dest[z+i]

There is some confusion in given answer so far. 到目前为止,给出的答案有些混乱。 It comes from fact that the strings read by fgets are not only null character terminated but also contain LINE_FEED character. 这是因为fgets读取的字符串不仅以null character结尾,而且还包含LINE_FEED字符。

1) Coppying 1)应对

dest[z+i+1]=src[z];  

has to be performed as: 必须执行为:

dest[z+i-1] = src[z];  

to eliminate ' \\n' == 0x0A 消除' \\n' == 0x0A

or preserving '\\n' as: 或将'\\n'保留为:

dest[z+i] = src[z]; 

2) We also have to properly terminate the concatenated string. 2)我们还必须正确终止连接的字符串。
Knowing that it i and j take under account '\\n' characters we have to terminated string accordingly: 知道ij考虑了'\\ n'个字符,我们必须相应地终止字符串:

   dest[i+j] = '\0' ;

3) In C90, the prototype is: 3)在C90中,原型为:

char *strcat(char *dest, const char *src);

The strcat() function shall return the pointer dest ; strcat()函数应返回指针dest the function has no failure mode and no error return. 该函数没有故障模式,也没有错误返回。

The improved program: 改进的程序:

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

char* strcat1(char* dest, const char* src);

char* strcat1(char* dest, const char* src){
   size_t i;
   size_t j;
   size_t z;

   i = strlen(dest);   //  Note: '\n' is included in the length count
   j = strlen(src);    //  Note: '\n' is included in the length count

   printf("i0=%zu, j0=%zu %X\n ", i, j, src[j-1] );

   for(z=0; z < j; z++){
        dest[z+i] = src[z];    
   }
   dest[i+j] = '\0' ;

  return dest;
}

int main(void){

   char str1[100];
   char str2[30];

   printf("put the first string:\n");
   fgets(str1, sizeof(str1), stdin);

   printf("\ninput the second string\n");
   fgets(str2, sizeof(str2), stdin);

   strcat1(str1,str2);

   printf("\n%s", str1);

   return 0;
}

Output: 输出:

put the first string:                                                                                                                           
1234                                                                                                                                            

input the second string                                                                                                                         
567890                                                                                                                                          
i0=5, j0=7 A                                                                                                                                    

1234                                                                                                                                            
567890                                                                                                                                          

There are some problems with your strcat1 function: 您的strcat1函数有一些问题:

  • The prototype should be char *strcat1(char *dest, const char *src); 原型应该是char *strcat1(char *dest, const char *src); as the function does not modify the source string. 因为该函数不会修改源字符串。

  • The characters should be copied at offset z + i into the dest array. 字符应该以偏移量z + i复制到dest数组中。 You currently copy the source string after the null terminator, so nothing appears when you print the destination array after the copy. 当前,您在空终止符之后复制源字符串,因此在复制后打印目标数组时,什么也不会出现。

  • You must copy the null terminator too, to ensure proper termination of the destination array. 您还必须复制空终止符,以确保目标数组正确终止。

  • You must return the pointer to the destination array. 您必须将指针返回到目标数组。

  • The index variables should have type size_t , that has a larger positive range than type int . 索引变量的类型应该为size_t ,其正范围大于int类型。

Here is a modified version: 这是修改后的版本:

char *strcat1(char *dest, const char *src) {
    size_t i = strlen(dest);
    size_t j = strlen(src);
    for (size_t z = 0; z <= j; z++) {
        dest[z + i] = src[z];    
    }
    return dest;
}

Note that you can implement this function with pointers, without strlen and with a single scan of the source string: 请注意,您可以使用指针来实现此功能,而不会被strlen ,并且只需对源字符串进行一次扫描即可:

char *strcat1(char *dest, const char *src) {
    char *p = dest;
    while (*p)
        p++;
    while ((*p++ = *src++) != '\0')
        continue;
    return dest;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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