In C/C++ you can initialize a set of variables to the same value by this syntax: a = b = c = 1;
Would this work for malloc
? IE something along the lines of:
char *a, *b;
a = b = malloc(SOME_SIZE * sizeof(char));
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?
If you break down your multiple assign line to single assignment lines, the solution would become more clear to you.
a = b = malloc(SOME_SIZE * sizeof(char));
OR
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.
Would this create two arrays of the same size, but each has its own memory?
No.
Or would it assign both arrays to the same place in address space?
It would assign both pointers to the same address, ie Both pointer a
and b
will point to the same allocated memory location.
In case of
int a, b, c;
a = b = c = 1;
compiler allocates memory for all variables a
, b
and c
to store an int
data type and then assigns 1
to each memory location. All memory location has its own copy of that data.
#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;
}
OutPut:
You Are Right
You Are Right
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.