Creating two arrays with malloc on one line

In C / C ++, you can initialize a set of variables to the same value using this syntax: a = b = c = 1;

Will this work for malloc

? I.E. something like:

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

      

Will this create two arrays of the same size, but each has its own memory? Or will it bind both arrays to the same location in the address space?

+3


source to share


3 answers


If you split your assignment line into separate assignment lines, the solution becomes clearer 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.

      

+4


source


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

Not.

Or will it assign both arrays to the same location in the address space?

He assigned both pointers to the same address, i.e. both pointers a

and b

will point to the same allocated memory location.



When

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

      

Compiler

allocates memory for all variables a

, b

and c

for storing the data type int

, and then assigns to 1

each memory location. All memory locations have their own copy of this data.

+3


source


#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're right

You're right

  • it is clear from this that both point to the same memory area.
+2


source







All Articles