How to return an array from a function

  Рет қаралды 66,723

CodeVault

CodeVault

Күн бұрын

At least once, we've all tried returning an array type from a function and it failed horribly. Here's how to do it properly.
Feel free to ask questions in the comments below!
---
IDE used in the video: sourceforge.net/projects/orwe...
Check out my course over on Udemy: www.udemy.com/quickstart-guid...

Пікірлер: 77
@dementekill
@dementekill 5 жыл бұрын
At last, someone who can explain this clearly Well done!
@amartuvshinpurevbaatar7280
@amartuvshinpurevbaatar7280 3 жыл бұрын
Thank you!!! whole day tried to figure out but the man explained in 7 mins
@vytautaskuklys3829
@vytautaskuklys3829 3 жыл бұрын
I really enjoy how clearly you communicate these topics :) Thank you, sir!
@moritzr466
@moritzr466 4 жыл бұрын
you absolute LEGEND, I spent soo many hours trying to realize why my program wasn't running holy shit, and now it all works thanks to you thank you so so so much bro!!!!!!
@nextzdota6392
@nextzdota6392 2 жыл бұрын
nice vid, reading answers on stack exchange just made me baning my head against the wall. This was clear and straight to the point. Thanks !!!
@ishaan600
@ishaan600 3 жыл бұрын
Thanks for this awesome explanation man! This really helped me as a beginner in c/c++ programing
@artcodezen
@artcodezen 4 жыл бұрын
Really nice explanation, I forget to do a malloc inside the function and my function returned nothing. Thank so much for the explanation. It's very clean o objective!
@Amin-vq3qd
@Amin-vq3qd 2 жыл бұрын
Thank you for sharing. I was just practicing some C programming and bumped into the same problem. This video saved me a lot of time. THX❤
@jesusstudentbrett
@jesusstudentbrett 2 жыл бұрын
this video was spot ON!! it helped me so much. Thank you.
@atiedebee1020
@atiedebee1020 3 жыл бұрын
Absolute legend, thanks for this video!
@mpi6416
@mpi6416 2 жыл бұрын
This clearly illustrated how I can use 2 dimensional tables with a pointer. Thank you very much.
@samleheny1429
@samleheny1429 Жыл бұрын
Aaaaaah! Pointers allow you to access and change global variables (or variables in the main function anyway) from inside another function. It all makes sense now!
@arunbm123
@arunbm123 2 жыл бұрын
Gentleman you are the best C teacher
@mariosantos3269
@mariosantos3269 5 жыл бұрын
Thanks! You helped me a lot
@canarese
@canarese 4 жыл бұрын
clear explanation of handling arrays in functions
@jesusstudentbrett
@jesusstudentbrett 2 жыл бұрын
another amazing C video. Thank you
@sophiagnetneva6861
@sophiagnetneva6861 3 жыл бұрын
this is exactly what i was looking for ty
@xfsn_archer75
@xfsn_archer75 Ай бұрын
Holy shit this blew my mind that you can do it this way. Poahhh well explained good sir
@04.nehalsingh12
@04.nehalsingh12 2 жыл бұрын
awesome tutorial sir
@tharunkumar6754
@tharunkumar6754 5 жыл бұрын
Thanks a lot man!
@madalinlupu625
@madalinlupu625 3 жыл бұрын
thanks this video really helped a lot
@gersonchadijunior7499
@gersonchadijunior7499 2 жыл бұрын
A friend of mine gave me an alternative solution by using static int arr[5]; this way you don't need to pass a solution argument in the function, something I've considered a bit confusing. But the explanation about the stack memory was quite a thing ! Thank you
@CodeVault
@CodeVault 2 жыл бұрын
Yes, that is also a solution. I talk about static variables a bit more in-depth here: code-vault.net/lesson/fnrghf6w4b:1603733522024
@matorumanovic8825
@matorumanovic8825 3 жыл бұрын
DUDE I LOVE YOU
@taukirlalwala2865
@taukirlalwala2865 3 жыл бұрын
Thanks man! it helped
@joestyles4639
@joestyles4639 3 жыл бұрын
thanks, very useful!
@zeyadmohamed9042
@zeyadmohamed9042 2 жыл бұрын
good work !
@santosbpm
@santosbpm 3 жыл бұрын
Oh! Thank you for this video.
@hashteraryal2311
@hashteraryal2311 Жыл бұрын
You are awesome, I think you can make your dev c++ look great it's classic theme without any editing
@tsrahul3849
@tsrahul3849 3 жыл бұрын
Thanks a lot man!!!
@eliascorrea220
@eliascorrea220 2 жыл бұрын
Nice video, thank to share it
@sglbl
@sglbl 4 жыл бұрын
Thank you sir.
@alexmorales1997
@alexmorales1997 3 жыл бұрын
FINALLY I CAN FIND SOMEONE WHO EXPLAIN IT NICE VIDEO!
@vasyltopalo8962
@vasyltopalo8962 3 жыл бұрын
Thank you
@geckobra
@geckobra 3 жыл бұрын
Is it necessary to have argc and char* argv[] on the int main?
@CodeVault
@CodeVault 3 жыл бұрын
No, not really
@limitless1692
@limitless1692 4 жыл бұрын
Hmmm Interesting ... i think i will try that Thanks :)
@thewolverine5591
@thewolverine5591 2 жыл бұрын
Thank u
@Greg0ryful1
@Greg0ryful1 4 жыл бұрын
I think you can also return the array if you define the local variable (arr) as 'static' variable
@CodeVault
@CodeVault 4 жыл бұрын
Yes you can. Although it's not always the best idea since the static variable makes the variable's memory location unchanged from call to call. So, if you call it twice to get two different arrays, the second call would modify the array from the first call. You'll need to be careful with that. I made a video on this topic: kzfaq.info/get/bejne/hdSXerigqrTLh6M.html
@bradpitt8967
@bradpitt8967 3 жыл бұрын
God bless you.
@amrnassar8417
@amrnassar8417 4 жыл бұрын
thank u
@neilpatil8551
@neilpatil8551 3 жыл бұрын
Really good video, man. Good explanation for anything you do. Insta subscribe from me
@ayeshaaj1787
@ayeshaaj1787 3 жыл бұрын
and if we want to pass this function as an argument to another function to calculate the sum of array elements int sum(int* result,int n) { int sum = 0; for (int i = 0; i < 10; i++) { sum += result[i]; //cout
@CodeVault
@CodeVault 3 жыл бұрын
I think you ignored the n argument which should be used here: for (int i = 0; i < n; i++)
@santosbpm
@santosbpm 3 жыл бұрын
In the video you teach very well how to do with one-dimensional arrays. Is it possible to perform a two-dimensional array return?
@CodeVault
@CodeVault 3 жыл бұрын
Yep. With the same exact concept. You just need to allocate the 2D arrays differently: code-vault.net/lesson/zgpd1zov1t:1603733527939
@santosbpm
@santosbpm 3 жыл бұрын
@@CodeVault I was already going crazy thinking about how to develop this solution. Thank you!
@yasminebouzguen7896
@yasminebouzguen7896 2 жыл бұрын
so what if i write a function to generate like a random array of integers. then i want To pass the result(random array) To another sorting function (eg: selection) and display the results is that possible .
@CodeVault
@CodeVault 2 жыл бұрын
Yes it is! I think you could simply use a dynamically allocated array there with a static size. Another option is to simply pass them through the arguments (the pointer to the array and the number of elements).
@LocksVid
@LocksVid 2 жыл бұрын
legend
@nikhilkumar4640
@nikhilkumar4640 4 жыл бұрын
6:50 int* result = malloc(sizeof(int)*5); malloc() gives the base address as a void pointer. How we are assigning it to integer pointer without typecasting?
@CodeVault
@CodeVault 4 жыл бұрын
The typecasting is only really advised when in C++. For C, it is automatically casted (like when assigning a float to an int or vice-versa) and casting it could hide certain bugs. For more details you can read the discussion here: stackoverflow.com/questions/20094394/why-do-we-cast-return-value-of-malloc?lq=1
@nikhilkumar4640
@nikhilkumar4640 4 жыл бұрын
@@CodeVault thanks
@Nietzscheboy1
@Nietzscheboy1 2 жыл бұрын
Nice solution to the problem... even if it's not a function that returns an array it achieves the desired goal. But I was wondering what your opinion is on actually returning an array from the function? Like... I did something like this in my code: int (*arr(void))[2] { static int x[2][2] = { {0,1}, {0,1} }; return x; } Function that takes no arguments and returns pointer to array of size 2. Works if you declare the two-d array as static. I think it's a rather funky function signature and I'm just an amateur programmer, so I'm worried I'm doing it wrong now that I watched this video, lol.
@CodeVault
@CodeVault 2 жыл бұрын
This should work. But there are many problems with the code. First, if you call this function multiple times. Suppose the function has an argument "a" and you modify this array in your function whenever you call it: x[0][0] = a; Well... now, if you call the function twice, you'll get one of the call modifying the other's call's result since, well, both calls return the same exact address. Here's the full code: int (*foo(int a))[2] { static int x[2][2] = { {0,1}, {0,1} }; x[0][0] = a; return x; } int main(int argc, char* argv[]) { void* arr = foo(1); printf("%d ", ((int*)arr)[0]); void* arr2 = foo(2); // this call modifies "arr" as well printf("%d ", ((int*)arr2)[0]); printf("%d ", ((int*)arr)[0]); // "arr" is modified even though we didn't do anything with it from calling foo(2) to here return 0; } Another issue is the return type. The return should actually be just a simple pointer to int since x[2][2] is actually an array of arrays but the compiler automatically converts array types to pointer types so it's easier to work with just plain pointers here
@CarlosDaniel-od7bx
@CarlosDaniel-od7bx 4 жыл бұрын
What if I wanted to return a 2D array from a function? Using malloc.
@CodeVault
@CodeVault 4 жыл бұрын
There are at least 2 ways you can do this. One is using everything exactly as in the video except for the indexing part. Instead of result[i] you'd have result[i * col_num + j] and iterating it with two for loops. col_num being the number of columns in the 2D array. And, of course, allocating enough memory with malloc(sizeof(int) * 5 * 5) (if you want a 5x5 array). Another way is to use a double pointer. Basically return a double pointer to an array of pointers that each point to an array of elements. Every pointer in that array representing a row. The latter is more complicated and I suggest using the former as you only really deal with one array, one pointer so only one free call.
@CarlosDaniel-od7bx
@CarlosDaniel-od7bx 4 жыл бұрын
@@CodeVault Thank you very much!
@DWEthiopia
@DWEthiopia 3 жыл бұрын
@@CodeVault Can you make a video showing how to return a 2d array?
@eddievertus3368
@eddievertus3368 4 жыл бұрын
vale wacho!
@ayabenabdi6458
@ayabenabdi6458 4 жыл бұрын
What about string arrays?
@CodeVault
@CodeVault 4 жыл бұрын
Similar to strings. Just pass in double pointers and allocate memory prior to calling the function.
@RedStoneMatt
@RedStoneMatt Жыл бұрын
What if you don't know the size of the resulting array in advance though? You'd have to use a malloc or new operator but then how are people using your code supposed to know that a malloc is in there ans that they need to free it?
@CodeVault
@CodeVault Жыл бұрын
Best option is to just have the function take an array and its capacity, then, the user will be responsible for allocating and deallocating the memory for the array (and it could also just be statically allocated)
@RedStoneMatt
@RedStoneMatt Жыл бұрын
@@CodeVault yeah but since you don't know the size of the array in advance, what size should the array you pass be of?
@CodeVault
@CodeVault Жыл бұрын
In these situations you usually allocate some space in the beginning that should fit all your data (capacity =/= size). If more space is needed you can return an error code
@patrickcordero6673
@patrickcordero6673 2 жыл бұрын
i tried it but instead of int array i used char array. All the values inside my char array is 0. I'm not sure why
@CodeVault
@CodeVault 2 жыл бұрын
Hmm... can you share the code here? Maybe I can help
@karnvarshneya3019
@karnvarshneya3019 2 жыл бұрын
how to return a char[ ] [ ] array from function ?
@CodeVault
@CodeVault 2 жыл бұрын
The easy way would be to just make a struct and statically allocate it, otherwise, you'd have to dynamically allocate a char**
@wahabfiles6260
@wahabfiles6260 4 жыл бұрын
So question remains, what is the best way to do it?
@CodeVault
@CodeVault 4 жыл бұрын
Sending it as a parameter is by far better, for 2 reasons: 1) The caller is responsible of deallocating the memory if needed 2) You're not limited to dynamically allocated memory for the array
@wahabfiles6260
@wahabfiles6260 4 жыл бұрын
@@CodeVault makes sense. Thanks. Subscribed today as soon as I saw you showing distinct ways and their pitfalls in the video!
@sahilkarn5912
@sahilkarn5912 2 жыл бұрын
Wouldn’t just declaring a pointer rather than array solve the issue of knowing the array size?
@CodeVault
@CodeVault 2 жыл бұрын
Where would the pointer point to? Can you send me an example so I can understand what you mean please?
@goaheadskinit
@goaheadskinit 6 ай бұрын
Thank you
Iterating over an array using pointers
6:27
CodeVault
Рет қаралды 19 М.
Arrays as function parameters in C
13:28
CodeVault
Рет қаралды 12 М.
Mama vs Son vs Daddy 😭🤣
00:13
DADDYSON SHOW
Рет қаралды 48 МЛН
How To Return An Array From A Function | C Programming Tutorial
13:01
Portfolio Courses
Рет қаралды 64 М.
do you know how "return" works under the hood? (are you SURE?)
5:08
Low Level Learning
Рет қаралды 351 М.
How to return and pass a struct to a function
13:30
CodeVault
Рет қаралды 30 М.
you will never ask about pointers again after watching this video
8:03
Low Level Learning
Рет қаралды 2,1 МЛН
Read an array of structs in C
12:37
CodeVault
Рет қаралды 31 М.
How To Return A String From A Function | C Programming Tutorial
13:51
Portfolio Courses
Рет қаралды 15 М.
Minimax: How Computers Play Games
14:37
Spanning Tree
Рет қаралды 200 М.
Generics: The most intimidating TypeScript feature
18:19
Matt Pocock
Рет қаралды 169 М.
Dynamically allocated multi-dimensional arrays in C
14:17
CodeVault
Рет қаралды 45 М.
The ORDER BY Algorithm Is Harder Than You Think
13:46
Tony Saro
Рет қаралды 59 М.