本文介绍了使用strcpy()与在C中复制char *地址的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个动态分配的数组. c

I have two dynamically allocated arrays. c

char **a = (char**)malloc(sizeof(char*) * 5));
char **b = (char**)malloc(sizeof(char*) * 5));

for (int i = 0; i < 7, i++) {
  a[i] = (char*)malloc(sizeof(char)*7);
  b[i] = (char*)malloc(sizeof(char)*7);
}

如果a[0]"hello\0",并且我想将a[0]复制到b[0]strcpy和指针分配是否是同一回事?例如:

If a[0] was "hello\0" and I wanted to copy a[0] to b[0], would strcpy and pointer assignment be the same thing? For example:

  1. strcpy(b[0], a[0])
  2. b[0] = a[0]
  1. strcpy(b[0], a[0])
  2. b[0] = a[0]

这两个人会做同样的事情吗?

Would these both do the same exact thing?

推荐答案

.两者都不一样.在这种情况下,strcpy(b[0], a[0])是将a[0]指向的字符串复制到b[0]的正确方法.

NO. Both are not same. In this case, strcpy(b[0], a[0]) is correct way to copy the string pointed by a[0] to b[0].

b[0] = a[0]的情况下,分配给b[0]的内存将丢失并且将导致内存泄漏.现在释放a[0]b[0]都将调用未定义的行为.这是因为它们两个都指向相同的内存位置,并且您释放了相同的已分配内存两次.

In case of b[0] = a[0], memory allocated to b[0] will lost and it will cause memory leak. Now freeing both of a[0] and b[0] will invoke undefined behavior. This is because both of them are pointing to same memory location and you are freeing same allocated memory twice.

注意:应该注意的是,如 Matt McNabb 在他的著作中指出的那样评论内存泄漏不会调用未定义的行为.

NOTE: It should be noted that, as Matt McNabb pointed in his comment, memory leak does not invokes undefined behavior.

这篇关于使用strcpy()与在C中复制char *地址的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:32