在C中使用concat而不使用字符串库函数或数组表示法

de90aj5v  于 2023-03-22  发布在  其他
关注(0)|答案(4)|浏览(195)

我的任务是能够concat两个字符串,并使用指针返回一个新的字符串。它应该返回一个新的字符串,但它目前返回一个空格。下面是我的代码:

char* concat(char* first, char* second){
    int string1Len = strlen(first);
    int string2Len = strlen(second);
    int length = string1Len + string2Len;
    char* string = malloc(sizeof(char)*length);
    int i;
    while(i < string1Len){
        *(string + i) = *first;
        first+= 1;
        i+= 1;
    }
    while( i < length){
        *(string + i) = *second;
        second+= 1;
        i+= 1;
    }

    return string;
}
carvr3hs

carvr3hs1#

除了unitialized int i = 0,你的代码看起来很好。这在我的机器上工作:

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

char* concat(char* first, char* second){
    int string1Len = strlen(first);
    int string2Len = strlen(second);
    int length = string1Len + string2Len;
    char* string = malloc(sizeof(char)*length + 1);
    assert(string);
    int i=0;
    while(i < string1Len){
        string[i] = *first;
        first+= 1;
        i+= 1;
    }
    while(i < length){
        string[i] = *second;
        second += 1;
        i += 1;
    }
    string[i] = '\0';
    return string;
}

int main(){
        char* x = "foo";
        char* y = "bar";
        printf("%s\n", concat(x, y));
        // prints 'foobar'
}

**P.S.**使用string[i]而不是*(string + i),它通常被认为更具可读性。

3okqufwl

3okqufwl2#

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

// You should use char const * as your function don't need to change the character of your input string
char *concat(char const *first, char const *second) { // put * on the variable name not the type
    assert(first && second); // test only include for debug build concat expect valid string
    size_t first_len = strlen(first); // strlen() return a size_t
    size_t second_len = strlen(second);
    // you could check for overflow case here
    size_t length = first_len + second_len; // malloc take a size_t as argument
    char *string = malloc(length + 1); // don't forget the nul terminate byte, sizeof(char) == 1
    if (!string) { // don't forget to check malloc() error
        return NULL;
    }
    size_t i = 0; // don't forget to initialize your variable
    while (*first) {
        string[i++] = *first++; // use [] notation is more readeable  in that case
    }
    while (*second) {
        string[i++] = *second++;
    }
    string[i] = '\0'; // never forget the nul terminate byte
    return string;
}

int main(void) {
    char *my_amazing_new_string = concat("Stack ", "Overflow");
    if (!my_amazing_new_string) {
        return EXIT_FAILURE;
    }
    printf("%s", my_amazing_new_string);
    free(my_amazing_new_string);
}
erhoui1w

erhoui1w3#

OP代码错误

Index未初始化

// int i;
int i = 0;

不追加或分配空字符

// char* string = malloc(sizeof(char)*length);
char* string = malloc(length + 1);
....
*(string + i) ='\0'; // add this
return string;

小事

sizeof(char)始终为1

//char* string = malloc(sizeof(char)*length);
char* string = malloc(length);  // Also +1 as noted above

int可能太窄

// int i;
size_t i;

不能使用strlen()

“没有字符串库函数”

分配缺少检查

char* string = malloc(...);
if (string == NULL) {  // add
  return NULL;
}

因为源字符串不修改,所以使用const

这允许更好地使用函数和潜在的优化。

//char* concat(char* first, char* second){
char* concat(const char* first, const char* second){

一些未经测试的替代代码。注意没有整型变量。

char* concat(const char* first, const char* second) {
  const char *p1 = first;
  while (*p1) {
    p1++;
  }
  const char *p2 = second;
  while (*p2) {
    p2++;
  }
  char* string = malloc((p1 - first) + (p2 - second) + 1);
  if (string) {
    char *ps = string;
    while ((*ps = *first++)) {
      ps++;
    }
    while ((*ps = *second++)) {
      ps++;
    }
  }
  return string;
}
piok6c0g

piok6c0g4#

String库?我从来没用过:P

char * concat(char * dest, const char * src)
{
    // creates a pointer to `dest` so we can return it from from its start position.
    char * ptr = dest;          
    // increment dest until the null-terminated which is 0 (false//loop stops).
    while (*dest) dest++;   
    // so we assign dest pointer to src pointer while incrementing them.    
    while (*dest++ = *src++);   
    // return the `dest` pointer.
    return ptr;                 
}

注意,你需要自己分配第一个参数,因为这个函数本身并不连接dest指针,所以返回值(是可选^^)。
我还注意到,由于某种原因......每个人都在函数本身中分配内存,所以我做了我的第二版本。然而,它不像第一个(尽管你需要返回值)。

char * concat(char * s1, const char * s2)
{
    size_t i = 0;
    // length of s1.
    while (*s1++) i++;
    size_t s1_len = i; i = 0;
    s1 -= s1_len + 1;
    // length of s2.
    while (*s2++) i++;
    size_t s2_len = i; i = 0;
    s2 -= s2_len + 1;
    // allocates memory.
    char * newStr = (char *)malloc((s1_len + s2_len)+1); // +1 is for the nul-terminated character.
    if(!newStr) return newStr; // if malloc fails, return (null) pointer.
    // points to position 0 of the 1st string.
    char * ptr = newStr;
    // copies the content of s1 to the new string
    while (*ptr++ = *s1++);
    // get back to the null-terminated to overwrite it.
    *ptr--;
    // concentrate
    while (*ptr++ = *s2++);
    // return the `newStr` pointer.
    return newStr;                  
}

相关问题