Realloc in C explained easy! 🚢

preview_player
Показать описание
#coding #programming #cprogramming

00:00:00 intro
00:00:53 setup
00:05:55 realloc demo

// realloc() = Reallocation.
// Resize previously allocated memory
// realloc(ptr, bytes)
Рекомендации по теме
Комментарии
Автор

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

int main(){

// realloc() = Reallocation.
// Resize previously allocated memory
// realloc(ptr, bytes)

int number = 0;
printf("Enter the number of prices: ");
scanf("%d", &number);

float *prices = malloc(number * sizeof(float));

if(prices == NULL){
printf("Memory allocation failed!\n");
return 1;
}

for(int i = 0; i < number; i++){
printf("Enter price #%d: ", i + 1);
scanf("%f", &prices[i]);
}

int newNumber = 0;
printf("Enter a new number of prices: ");
scanf("%d", &newNumber);

float *temp = realloc(prices, newNumber * sizeof(float));

if(temp == NULL){
printf("Could not reallocate memory!\n");
}
else{
prices = temp;
temp = NULL;

for(int i = number; i < newNumber; i++){
printf("Enter price #%d: ", i + 1);
scanf("%f", &prices[i]);
}

for(int i = 0; i < newNumber; i++){
printf("$%.2f ", prices[i]);
}
}

free(prices);
prices = NULL;

return 0;
}

BroCodez
Автор

You know sh*t is real when Bro warns you it won't be easy

clutchyfinger
Автор

"Thank you for your videos man, you don’t know how much you're helping me. I can’t afford extra tuition and since I work while in high school, it’s hard to keep up with everything. I’m currently watching your full Python course and it’s been a lifesaver. In class we’re doing topics like object-oriented programming (OOP), recursion, SQL, relational databases, binary trees, trees in general, graph algorithms, stacks & queues, dictionaries, divide and conquer, dynamic programming, and text search. Would love to see more content on those in Python if you ever cover them! (Python coding specifically—I don't struggle with the concepts as much, it’s just hard to visualize the actual coding process.) No pressure at all, just really appreciate your work 🙏

OhBleh
Автор

Yk it’s hard when bro code calls it hard

Hnxzxvr
Автор

When the full course going to be available?

ShubhamRanjan-ij
Автор

In the last example, reallocating from 5 to 3, those 2 "memory blocks" we let go are internally freed right? No memory leaks?

valentrix
Автор

if i have

char *n = malloc(10 * sizeof(char));
memset(n, 'h', 9);
n[9] = 0;
realloc(n, 100 * sizeof(char));
free(n);

how can i memset n without deleting the contents?

tierthetora
Автор

Amazing vid you’re saving me, is the full course going to be available this week?

cduw
Автор

Bro change it to “explained easy” WE’VE ALREADY SEEN IT MWA HA HA HA

Hnxzxvr
Автор

I am the third comment
Now i can die in peace

zyadoreaby