gpt4 book ai didi

c - 写一个字符串连接 : How to convert character array to pointer

转载 作者:太空宇宙 更新时间:2023-11-04 04:10:49 25 4
gpt4 key购买 nike

我正在学习 C,我编写了以下 strcat 函数:

char * stringcat(const char* s1, const char* s2) {

int length_of_strings = strlen(s1) + strlen(s2);
char s3[length_of_strings + 1]; // add one for \0 at the end

int idx = 0;

for(int i=0; (s3[idx]=s1[i]) != 0; idx++, i++);
for(int i=0; (s3[idx]=s2[i]) != 0; idx++, i++);
s3[idx+1] = '\0';

// s3 is a character array;
// how to get a pointer to a character array?
char * s = s3;

return s;

}

我觉得奇怪的部分是我必须将字符数组“重新分配”给指针,否则 C 会提示我返回的是一个内存地址。我还尝试将返回值“转换”为 (char *) s3,但这也没有用。

进行这种“转换”的最常用方法是什么?这是 C 程序中的常见模式吗?

最佳答案

有很多方法可以处理这种情况,但在函数内部返回一个指向堆栈分配内存的指针不是其中之一(行为是未定义的;一旦函数返回,就认为这 block 内存是不可触及的)。

一种方法是使用 malloc 分配堆内存在函数内部,构建结果字符串,然后返回指向新分配内存的指针,并理解调用者负责释放内存。

这是一个例子:

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

char *stringcat(const char* s1, const char* s2) {
int i = 0;
int s1_len = strlen(s1);
int s2_len = strlen(s2);
char *result = malloc(s1_len + s2_len + 1);
result[s1_len+s2_len] = '\0';

for (int j = 0; j < s1_len; j++) {
result[i++] = s1[j];
}

for (int j = 0; j < s2_len; j++) {
result[i++] = s2[j];
}

return result;
}

int main(void) {
char *cat = stringcat("hello ", "world");
printf("%s\n", cat); // => hello world
free(cat);
return 0;
}

另一种方法是由调用者处理所有的内存管理,这类似于strcat的方式。行为:

/* Append SRC on the end of DEST.  */
char *
STRCAT (char *dest, const char *src)
{
strcpy (dest + strlen (dest), src);
return dest;
}

man说:

The strcat() function appends the src string to the dest string, overwriting the terminating null byte ('\0') at the end of dest, and then adds a terminating null byte. The strings may not overlap, and the dest string must have enough space for the result. If dest is not large enough, program behavior is unpredictable; buffer overruns are a favorite avenue for attacking secure programs.

关于c - 写一个字符串连接 : How to convert character array to pointer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57830197/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com