简体   繁体   English

使用memcpy将两个char *复制到** buff-C语言

[英]Copy two char* to **buff with memcpy - C language

I got two char pointer: 我有两个char指针:

char *a="A";
char *b="B";

And a pointer to pointer buffer: 还有一个指向指针缓冲区的指针:

char **buf = malloc(sizeof(char*)*2);

And I want use memcpy to copy two variables to buf: 我想使用memcpy将两个变量复制到buf:

memcpy(*buf, &a, sizeof(char*));
memcpy(*buf, &b, sizeof(char*));

but it replace first variable.. 但是它将替换第一个变量。

how can I copy two? 如何复制两个?

What is it you actually want to do? 您实际上想做什么?

With

char **buf = malloc(sizeof(char*)*2);

memcpy(*buf, &a, sizeof(char*));
memcpy(*buf, &b, sizeof(char*));

unless you omitted some initialisation in between, you get undefined behaviour. 除非您在两者之间省略了一些初始化,否则您将获得不确定的行为。 The contents of the malloc ed memory is unspecified, so when *buf is interpreted as a void* in memcpy , that almost certainly doesn't yield a valid pointer, and the probability that it is a null pointer is not negligible. malloc内存的内容未指定,因此当*bufmemcpy被解释为void*时,几乎可以肯定不会产生有效的指针,并且它是空指针的可能性不可忽略。

If you just want buf to contain the two pointers, after the malloc 如果只希望buf包含两个指针,则在malloc

buf[0] = a;
buf[1] = b;

is the simplest and cleanest solution, but 是最简单,最干净的解决方案,但是

memcpy(buf, &a, sizeof a);
memcpy(buf + 1, &b sizeof b);

would also be valid (also with &buf[1] instead of buf + 1 . 也将有效(也可以使用&buf[1]代替buf + 1

If you want to concatenate the strings a and b point to, you're following a completely wrong approach. 如果要连接字符串ab指向的字符串,则使用完全错误的方法。 You'd need a char* pointing to a sufficiently large area to hold the result (including the 0-terminator) and the simplest way would be using strcat . 您需要一个char*指向足够大的区域来保存结果(包括0终止符),最简单的方法是使用strcat

I tried your program with my own test code: I hope this helps: 我用自己的测试代码尝试了您的程序:希望对您有所帮助:

#define MAX_LENGTH 10
#define ARRAY_LENGTH 2
int main(int argc, char *argv[])
{
    char *a = "A";
    char *b = "B";
    char **buf = (char **)malloc(sizeof(char*)*ARRAY_LENGTH);
    *buf = (char *)malloc(sizeof(char) * MAX_LENGTH);
    *(buf+1) = (char *)malloc(sizeof(char) * MAX_LENGTH);
    memset(buf[0],0,10);
    memset(buf[1],0,10);
    memcpy(buf[0],a,strlen(a));
    memcpy(buf[1],b,strlen(b));
    printf("%s %s",buf[0],buf[1]);
    free(buf[0]);
    free(buf[1]);
        free(buf)
    return 0;
}

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

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