Bellow I show some code that I got from a tutorial.
I am interested in understanding what are some changes that I can make to this code so that I will end up in the block:
Code:
if (ptr == NULL) {
printf("Memory not allocated.\n");
exit(0);
The code:
Code:
#include <stdio.h>
#include <stdlib.h>
int main() {
// This pointer will hold the
// base address of the block created
int* ptr;
int n, i, sum = 0;
// Get the number of elements for the array
n = 5;
printf("Enter 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]);
}
}
}
So I don't want to receive the message: "Memory successfully allocated using malloc", but "Memory not allocated"