Creating two arrays with malloc on the same line

1.3k views Asked by At

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? I.E. 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?

3

There are 3 answers

0
Abhineet On BEST ANSWER

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.
0
haccks On

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, i.e. 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.

1
Nishant On
#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

  • from this its clear that Both Points to the Same Memory Area.