在同一行上使用 malloc 创建两个数组

Creating two arrays with malloc on the same line

在 C/C++ 中,您可以通过以下语法将一组变量初始化为相同的值:a = b = c = 1;

这对 malloc 有用吗? IE。类似于:

char *a, *b;
a = b = malloc(SOME_SIZE * sizeof(char));

这会创建两个相同大小的数组,但每个数组都有自己的内存吗?或者它将两个数组分配到地址 space 中的同一个位置?

Would this create two arrays of the same size, but each has its own memory?

没有。

Or would it assign both arrays to the same place in address space?

它将两个指针分配给相同的地址,即指针 ab 将指向相同的分配内存位置。

如果

int a, b, c;
a = b = c = 1;  

编译器为所有变量 abc 分配内存以存储 int 数据类型,然后将 1 分配给每个内存位置.所有内存位置都有自己的数据副本。

如果将多个分配行分解为单个分配行,解决方案对您来说会更加清晰。

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

b = malloc(SOME_SIZE * sizeof(char)); // b points to the alloced memory
a = b; // a got the value of b i.e., a points to where b is pointing.
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
using namespace std;
#define SOME_SIZE 20
int main()
{

      char *a, *b;
      a = b = (char *)malloc(SOME_SIZE * sizeof(char));
      strcpy(a,"You Are Right");

      cout << &(*a) << endl;
      cout << &(*b) << endl;
      return 0;
}

输出:

你是对的

你是对的

  • 由此可见两者指向同一内存区域。