How to return an array from a function

Поделиться
HTML-код
  • Опубликовано: 30 янв 2025

Комментарии • 78

  • @amartuvshinpurevbaatar7280
    @amartuvshinpurevbaatar7280 3 года назад +4

    Thank you!!! whole day tried to figure out but the man explained in 7 mins

  • @vytautaskuklys3829
    @vytautaskuklys3829 3 года назад +8

    I really enjoy how clearly you communicate these topics :) Thank you, sir!

  • @moritzr466
    @moritzr466 5 лет назад +2

    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 3 года назад +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 !!!

  • @artcodezen
    @artcodezen 4 года назад +2

    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❤

  • @arunbm123
    @arunbm123 3 года назад

    Gentleman you are the best C teacher

  • @mpi6416
    @mpi6416 2 года назад

    This clearly illustrated how I can use 2 dimensional tables with a pointer. Thank you very much.

  • @ishaan600
    @ishaan600 4 года назад +3

    Thanks for this awesome explanation man! This really helped me as a beginner in c/c++ programing

  • @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!

  • @xfsn_archer75
    @xfsn_archer75 7 месяцев назад

    Holy shit this blew my mind that you can do it this way. Poahhh well explained good sir

  • @jesusstudentbrett
    @jesusstudentbrett 2 года назад

    this video was spot ON!! it helped me so much. Thank you.

  • @canarese
    @canarese 4 года назад

    clear explanation of handling arrays in functions

  • @atiedebee1020
    @atiedebee1020 3 года назад +1

    Absolute legend, thanks for this video!

  • @hashteraryal2311
    @hashteraryal2311 2 года назад

    You are awesome, I think you can make your dev c++ look great
    it's classic theme without any editing

  • @gersonchadijunior7499
    @gersonchadijunior7499 3 года назад

    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  3 года назад +1

      Yes, that is also a solution. I talk about static variables a bit more in-depth here: code-vault.net/lesson/fnrghf6w4b:1603733522024

  • @04.nehalsingh12
    @04.nehalsingh12 3 года назад

    awesome tutorial sir

  • @alexmorales1997
    @alexmorales1997 4 года назад +1

    FINALLY I CAN FIND SOMEONE WHO EXPLAIN IT
    NICE VIDEO!

  • @sophiagnetneva6861
    @sophiagnetneva6861 3 года назад +1

    this is exactly what i was looking for ty

  • @jesusstudentbrett
    @jesusstudentbrett 2 года назад

    another amazing C video. Thank you

  • @mariosantos3269
    @mariosantos3269 6 лет назад +3

    Thanks! You helped me a lot

  • @Greg0ryful1
    @Greg0ryful1 4 года назад +1

    I think you can also return the array if you define the local variable (arr) as 'static' variable

    • @CodeVault
      @CodeVault  4 года назад +3

      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: ruclips.net/video/OngGUoENgWo/видео.html

  • @santosbpm
    @santosbpm 3 года назад +1

    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 года назад +2

      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!

  • @matorumanovic8825
    @matorumanovic8825 3 года назад

    DUDE I LOVE YOU

  • @geckobra
    @geckobra 4 года назад +1

    Is it necessary to have argc and char* argv[] on the int main?

  • @madalinlupu625
    @madalinlupu625 3 года назад

    thanks this video really helped a lot

  • @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 года назад +1

      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

  • @zeyadmohamed9042
    @zeyadmohamed9042 2 года назад

    good work !

  • @taukirlalwala2865
    @taukirlalwala2865 3 года назад

    Thanks man! it helped

  • @yasminebouzguen7896
    @yasminebouzguen7896 3 года назад

    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  3 года назад +1

      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).

  • @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++)

  • @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

  • @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

  • @eliascorrea220
    @eliascorrea220 2 года назад

    Nice video, thank to share it

  • @tharunkumar6754
    @tharunkumar6754 5 лет назад +1

    Thanks a lot man!

  • @santosbpm
    @santosbpm 3 года назад

    Oh! Thank you for this video.

  • @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 4 года назад

      @@CodeVault Can you make a video showing how to return a 2d array?

  • @AutusDeletus98
    @AutusDeletus98 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

  • @joestyles4639
    @joestyles4639 4 года назад

    thanks, very useful!

  • @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.

  • @ironmonkey1990
    @ironmonkey1990 5 месяцев назад

    thank you!

  • @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?

  • @sglbl
    @sglbl 4 года назад

    Thank you sir.

  • @vasyltopalo8962
    @vasyltopalo8962 3 года назад

    Thank you

  • @wahabfiles6260
    @wahabfiles6260 4 года назад

    So question remains, what is the best way to do it?

    • @CodeVault
      @CodeVault  4 года назад +1

      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!

  • @limitless1692
    @limitless1692 5 лет назад

    Hmmm
    Interesting ... i think i will try that
    Thanks :)

  • @karnvarshneya3019
    @karnvarshneya3019 3 года назад

    how to return a char[ ] [ ] array from function ?

    • @CodeVault
      @CodeVault  3 года назад

      The easy way would be to just make a struct and statically allocate it, otherwise, you'd have to dynamically allocate a char**

  • @bradpitt8967
    @bradpitt8967 4 года назад

    God bless you.

  • @LocksVid
    @LocksVid 2 года назад

    legend

  • @neilpatil8551
    @neilpatil8551 4 года назад

    Really good video, man. Good explanation for anything you do. Insta subscribe from me

  • @amrnassar8417
    @amrnassar8417 5 лет назад

    thank u

  • @eddievertus3368
    @eddievertus3368 4 года назад

    vale wacho!

  • @tsrahul3849
    @tsrahul3849 4 года назад

    Thanks a lot man!!!

  • @goaheadskinit
    @goaheadskinit 11 месяцев назад

    Thank you

  • @thewolverine5591
    @thewolverine5591 2 года назад

    Thank u