xDaizu
0
Q:

how to use malloc in c

int main(int argc, char *argv[])
{
    int* memoireAllouee = NULL;

    memoireAllouee = malloc(sizeof(int));
    if (memoireAllouee == NULL) // Si l'allocation a échoué
    {
        exit(0); // On arrête immédiatement le programme
    }

    // On peut continuer le programme normalement sinon

    return 0;
}
0
//malloc or "memory allocation" reserves a part of the memory

pointer = (cast-type*) malloc(byte-size)
  
//Example
ptr = (int*) malloc(100 * sizeof(int));

Since the size of int is 4 bytes, this statement will allocate 400 bytes
of memory. And, the pointer ptr holds the address of the first byte in
the allocated memory.
4
#include <stdlib.h>

void *malloc(size_t size);

void exemple(void)
{
  char *string;
  
  string = malloc(sizeof(char) * 5);
  string[0] = 'H';
  string[1] = 'e';
  string[2] = 'y';
  string[3] = '!';
  string[4] = '\0';
  printf("%s\n", string);
}

/// output : "Hey!"
2
int* a =(int*)malloc(sizeof(int))
1
ptr = (cast-type*) malloc(byte-size)
0
ptr = (castType*) malloc(size);
0
In C, the library function malloc is used to allocate a block of memory on the heap. The program accesses this block of memory via a pointer that malloc returns. When the memory is no longer needed, the pointer is passed to free which deallocates the memory so that it can be used for other purposes.
0

New to Communities?

Join the community