0

i am new to c

#include <stdlib.h>
#include <stdio.h>

int main() {
    int *var = (int *) malloc(sizeof(int) * 2)  ;

    *var = 22;

    printf("%d \n" , var);

    free(var);

    return 0;
}

is this the right way to assign a value to a variable created using malloc? because i've been trying to give it a value by doing

var = 22;

because when creating a 'string' in c and assigning a value to it it is done like this

char *var;
var = "birds are dying";

not like

*var= "birds are dying";
  • Compile with `-Wall -Wextra`. The warnings will tell you what's wrong. Also, [don't cast malloc](https://stackoverflow.com/q/605845/6699433) And you also might want to find a tutorial or something about pointers. – klutt Oct 19 '20 at 22:02

1 Answers1

3

is this the right way to assign a value to a variable created using malloc?

For starters there is no variable crated using malloc. Variables are created by declarations.

In this line

int *var = (int *) malloc(sizeof(int) * 2)  ;

there is declared the variable var having the type int * that is initialized by the address of the dynamically allocated memory using malloc for two objects of the type int.

To access the dynamically allocated objects you can use the subscript operator like

var[0] = 22;
var[1] = 33;

that is the same if to write

*var = 22;
*( var + 1 ) = 33;

So to output the values of the allocated objects you can write

printf("%d \n" , *var);

or

printf("%d \n" , var[0]);

or

printf("%d \n" , var[1]);

or

printf("%d \n" , *( var + 1 ));

As for this code snippet

char *var;
var = "birds are dying";

then the variable var itself that is assigned with the address of the first character of the string literal "birds are dying" not an object that could be pointed to by the variable var.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335