如何在没有内部函数的情况下在 C 中复制字符数组



这是我的代码

char function(char *dst)
{
int i;
char *arr;
i = 0;
while(dst[i] != '')
{
arr[i] = dst[i];
i++;
}
dst[i] != ''
return(arr);
}
int main(void)
{
char a[] ="asdf"
printf("%s", function(a);
}

我想将*dst复制到空*arr但我的代码不起作用。 我无法理解。 如何在 C(ex_strcpy,memspy... 谢谢

除了缺少;并确保传递给函数的string始终是''终止的(否则程序会遇到副作用strcpy原因)。 并返回char*而不是 char,您错过了为arr分配内存

// return char * instead of char
char* function(char *dst)
{
// Note - sizeof(dst) wont work
// Neither does sizeof(dst)/sizeof(char)
// allocate one extra for ''
size_t size_to_alloc = (strlen(dst) + 1) * (sizeof *arr);
char *arr = malloc( size_to_alloc  );
char *p = arr;
for ( ; *dst ; p++, dst++)
*p = *dst;
*p = '';
return(arr);
} 

如果要动态复制数组,则需要使用 malloc 或其他等效项为 char 数组分配内存。确保在完成内存后释放内存。我建议阅读一些关于 malloc 的文章并在 c 中分配内存。

这可能是一个不错的起点。

https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/

#include <stdio.h>
#include <stdlib.h>
char* function(char *dst, size_t length) {
int i;
// Allocating the memory needed for the char array.
char *arr = (char*) malloc (sizeof(char) * length);
i = 0;
while(dst[i] != '') {
arr[i] = dst[i];
i++;
}
arr[length - 1] = '';
return(arr);
}
int main(void) {
char a[] ="asdf";
// Getting length of the array
size_t length = sizeof(a) / sizeof(a[0]);
char* val = function(a, length);
printf("%s", val);
free(val);
}

您缺少内存分配,基本上是尝试重新编码 strdup。见下文:

char    *ft_strdup(const char *src)
{
char    *dst;
int     len;
len = 0;
while (src[len]) // no inner function
++len;
if (!(dst = malloc(sizeof(char) * (len + 1)))) // need 1 extra char to NULL terminate.
return NULL;
dst[len] = '';
while (--len > -1)
dst[len] = src[len];
return dst;
}

请注意,编写您自己的 strdup 版本并将其包含在程序库中是有意义的,因为此函数不是 C 标准的一部分。

如果有可能在不使用 c 函数的情况下复制字符串,也许可以通过执行 c 函数所做的工作来完成。

看看StrcPy做了什么可能会很有趣: https://code.woboq.org/userspace/glibc/string/strcpy.c.html

char *
STRCPY (char *dest, const char *src)
{
return memcpy (dest, src, strlen (src) + 1);
}

事实上,它使用memcpy:https://code.woboq.org/gcc/libgcc/memcpy.c.html

这里的魔力...

void *
memcpy (void *dest, const void *src, size_t len)
{
char *d = dest;
const char *s = src;
while (len--)
*d++ = *s++;
return dest;
}

和斯特伦:https://code.woboq.org/userspace/glibc/string/strlen.c.html

您可以使用memcpy()直接复制内存,例如在 Memcpy、字符串和终止符中,以及 https://www.gnu.org/software/libc/manual/html_node/Copying-Strings-and-Arrays.html 在 C 中,任何字符串都必须以终止(哨兵值)

#include<stdio.h>
#include<string.h>
int main()
{
char source[] = "World";   
char destination[] = "Hello ";   
/* Printing destination string before memcpy */
printf("Original String: %sn", destination);
/* Copies contents of source to destination */
memcpy (destination, source, sizeof(source)); 
/* Printing destination string after memcpy */
printf("Modified String: %sn", destination);
return 0;
}

来源 : https://www.educative.io/edpresso/c-copying-data-using-the-memcpy-function-in-c

最新更新