String concatenation without strcat in C

前端 未结 7 803
伪装坚强ぢ
伪装坚强ぢ 2021-01-13 13:44

I am having trouble concatenating strings in C, without strcat library function. Here is my code

#include
#include
#include<         


        
7条回答
  •  时光取名叫无心
    2021-01-13 14:41

    Problems:

    1. length isn't a function. strlen is, but you probably shouldn't call it in a loop - b1's length won't change on us, will it? Also, it returns a size_t, which may be the same size as int on your platform but will be unsigned. This can (but usually won't) cause errors, but you should do it right anyway.
    2. a1 only has enough space for the first string, because the compiler doesn't know to allocate extra stack space for the rest of the string since. If you provide an explicit size, like [100], that should be enough for your purposes. If you need robust code that doesn't make assumptions about what is "enough", you should look into malloc and friends, though that may be a lesson for another day.
    3. Your loop stops too early. i < b1_len (assuming you have a variable, b1_len, that was set to the length of b1 before the loop began) would be sufficient - strlen doesn't count the '\0' at the end.
    4. But speaking of counting the '\0' at the end, a slightly more efficient implementation could use sizeof a1 - 1 instead of strlen(a1) in this case, since a1 (and b1) are declared as arrays, not pointers. It's your choice, but remember that sizeof won't work for pointers, so don't get them mixed up.
      EDIT: New problems:
    5. char *p = malloc(/*some*/); p = /* something */ is a problem. = with pointers doesn't copy contents, it copies the value, so you're throwing away the old pointer value you got from malloc. To copy the contents of a string into a char * (or a char [] for that matter) you'd need to use strcpy, strncpy, or (my preference) memcpy. (Or just a loop, but that's rather silly. Then again, it may be good practice if you're writing your own strcat.)
    6. Unless you're using C++, I wouldn't cast the return value of malloc, but that's a religious war and we don't need one of those.
    7. If you have strdup, use it. If you don't, here is a working implementation:

      char *strdup(const char *c)
      {
          size_t l = strlen(c);
          char *d = malloc(l + 1);
          if(d) memcpy(d, c, l + 1);
          return d;
      }
      

      It is one of the most useful functions not in the C standard library.

提交回复
热议问题