“Alokasi memori dinamis c” Kode Jawaban

malloc di c

#include <stdlib.h>

void *malloc(size_t size);

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

/// output : "Hey!"
Thurger

memori dinamis di c

// Program to calculate the sum of n numbers entered by the user

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

int main() {
  int n, i, *ptr, sum = 0;

  printf("Enter number of elements: ");
  scanf("%d", &n);

  ptr = (int*) malloc(n * sizeof(int));
 
  // if memory cannot be allocated
  if(ptr == NULL) {
    printf("Error! memory not allocated.");
    exit(0);
  }

  printf("Enter elements: ");
  for(i = 0; i < n; ++i) {
    scanf("%d", ptr + i);
    sum += *(ptr + i);
  }

  printf("Sum = %d", sum);
  
  // deallocating the memory
  free(ptr);

  return 0;
}
Defiant Dotterel

Alokasi memori dinamis c

string* str_arr = nullptr;
str_arr = new string[10];

//initialize
str_arr[0] = "Hello";
str_arr[1] = " World!";
Magnificent Millipede

Alokasi memori dinamis c

#include <stdio.h>
#include <stdlib.h>
 
int main()
{
 
    // This pointer will hold the
    // base address of the block created
    int* ptr;
    int n, i;
 
    // Get the number of elements for the array
    printf("Enter number of elements:");
    scanf("%d",&n);
    printf("Entered number of elements: %d\n", n);
 
    // Dynamically allocate memory using malloc()
    ptr = (int*)malloc(n * sizeof(int));
 
    // Check if the memory has been successfully
    // allocated by malloc or not
    if (ptr == NULL) {
        printf("Memory not allocated.\n");
        exit(0);
    }
    else {
 
        // Memory has been successfully allocated
        printf("Memory successfully allocated using malloc.\n");
 
        // Get the elements of the array
        for (i = 0; i < n; ++i) {
            ptr[i] = i + 1;
        }
 
        // Print the elements of the array
        printf("The elements of the array are: ");
        for (i = 0; i < n; ++i) {
            printf("%d, ", ptr[i]);
        }
    }
 
    return 0;
}
Dead Dunlin

Jawaban yang mirip dengan “Alokasi memori dinamis c”

Pertanyaan yang mirip dengan “Alokasi memori dinamis c”

Lebih banyak jawaban terkait untuk “Alokasi memori dinamis c” di C++

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya