How To Return An Array From A Function | C Programming Tutorial

แชร์
ฝัง
  • เผยแพร่เมื่อ 12 ม.ค. 2025
  • How to return an array from a function in C. We technically cannot return an array from a function in C, but we can use pointers, and different approaches including dynamic memory allocation and static variables, to achieve something effectively similar. Source code: github.com/por.... Check out www.portfolioc... to build a portfolio that will impress employers!

ความคิดเห็น • 162

  • @rabbitcreative
    @rabbitcreative 11 หลายเดือนก่อน +30

    Neat. I think of it as two opposing thought-processes:
    1. This function returns an array.
    2. This function is given an array to write to.

    • @andredcavalcante
      @andredcavalcante 8 หลายเดือนก่อน

      The problem is think that the value of return statement IS the function return. It's not. The return statement was create in the sense to provide a single value that the function return to callee to enable some decision there. Data pass to and retrieve from a function must be made through function arguments, by value or by reference (pointer to). Understand this Will make your life easier in C.

  • @neelakantannilakantanswami4031
    @neelakantannilakantanswami4031 11 หลายเดือนก่อน +13

    I have 10 years of Experience in C Programming. I have never Seen such Clear Explanations in the entire you tube. Thanks to Portfolio Courses. You are really Awesome.

  • @siya.abc123
    @siya.abc123 ปีที่แล้ว +34

    I'm learning C again after some years, so glad this channel exists because the teachings are super clear to me

    • @PortfolioCourses
      @PortfolioCourses  ปีที่แล้ว

      I’m glad you’re finding the videos clear Siya! :-)

    • @siya.abc123
      @siya.abc123 ปีที่แล้ว

      @@PortfolioCourses wow thanks for the reply! I love your style and pace. I wish I knew about your much earlier in my career, I would definitely be a C programmer. But C# and JavaScript pay the bills for now 😅
      Thank you for the great content, I've been binge watching for the past couple of weeks

  • @ellipszia
    @ellipszia 2 ปีที่แล้ว +8

    Thank you!! Theese videos are filling big gaps in youtube!

  • @AK-vx4dy
    @AK-vx4dy 11 หลายเดือนก่อน +3

    I'm not regular C programmer but i'm old enough to touch it and i say, *very* clear explanations of some C quirks, wich can let some one really undrestand what is going on.
    Thank you and keep going!

  • @fifaham
    @fifaham 5 หลายเดือนก่อน +1

    Watching those great videos more than once will make you a better programmer.

  • @hansformer9556
    @hansformer9556 11 หลายเดือนก่อน +12

    I think more important for the _static_ approach is, that every function call will reference the *same* array.
    So when you call set_array(4) and later on set_array(5), the first array will be changed too.
    That produces very hard to find bugs because of the sideeffects.
    A topic that would be great for another video.

    • @PortfolioCourses
      @PortfolioCourses  11 หลายเดือนก่อน +4

      A video on side effects in general is something I've been thinking of.

  • @t0rg3
    @t0rg3 11 หลายเดือนก่อน +13

    I’m a bit disappointed that you didn’t put more emphasis on properly pairing up malloc and free calls. In my experience it helps putting both in the same scope. So in your example one would move the malloc call out of the function and into main.

    • @acherongoon
      @acherongoon 11 หลายเดือนก่อน +2

      A poibt that needs stressing for the static method is that you have a singleton array, there is only one array and more cannot be made.

  • @poenanster5285
    @poenanster5285 2 ปีที่แล้ว +1

    bruh, I've been looking for this for an absurd amount of time, this is much easier than messing with static ints' and those sorts of things..

    • @PortfolioCourses
      @PortfolioCourses  2 ปีที่แล้ว +2

      I'm glad you found the video and that it helped you out! :-)

  • @davidharper1152
    @davidharper1152 10 หลายเดือนก่อน

    Great explanation, particularly the inclusion of static local variables which are encapsulated but not dynamic... Nice Work

  • @fxs2008
    @fxs2008 5 หลายเดือนก่อน +3

    When passing a pointer to an array, please don't forget to pass the number of items that has the array, otherwise you might access memory outside of the array and have segfault. The example in the video implies that the array length is 5 so it's hardcoded everywhere and there's no issue here.

  • @yxyk-fr
    @yxyk-fr 11 หลายเดือนก่อน +5

    8:00 congratulations! you reinvented memset() ;-)

  • @lucasgroves137
    @lucasgroves137 ปีที่แล้ว +2

    🎯 Finally some clarity on static vs dynamic allocation. 👍👍

    • @PortfolioCourses
      @PortfolioCourses  ปีที่แล้ว +1

      I’m glad the video was helpful in clearing things up Lucas! :-)

  • @fifaham
    @fifaham ปีที่แล้ว +2

    Educational videos like those, of Kevin, are very hard to find anywhere, not even in the universities. Kevin deserves a lot of appreciation.

    • @PortfolioCourses
      @PortfolioCourses  ปีที่แล้ว +1

      I'm glad you enjoy the content Firas, thank you for being such a great supporter! :-)

  • @oracle_stm2711
    @oracle_stm2711 2 ปีที่แล้ว +3

    Man you just saved me because there are no videos about it on TH-cam. Man, thank you very much (I'm in physics, in the third year) ;)

  • @RaviKumar-gh9oh
    @RaviKumar-gh9oh ปีที่แล้ว +2

    you are the best Sirrrr , nobody like you taught me these concept , plz carry on your way of teaching is unbelievable . i have huge respect for u sir.please don't leave us in this journey.
    Thanku sir🙂

  • @TheKhalamar
    @TheKhalamar 10 หลายเดือนก่อน

    The huge disadvantage of the static approach is that the same array is shared between the calls. That means that if you call the function twice with different values, the values of the first array will be changed to the new value during the second call (because both have the same address)

  • @しめい-l4m
    @しめい-l4m 11 หลายเดือนก่อน +1

    11:16
    just wondering, doesn't the compiler think the size of result is sizeof(int) and only free the first element of the array, and leak the rest?
    or is C compiler smart enough to guess that result "integer" has 5 elements in it?

    • @psyience3213
      @psyience3213 11 หลายเดือนก่อน +3

      when you call malloc some extra information is stored with it like the block size. This block size is used to determine how much memory to free.

    • @cinderwolf32
      @cinderwolf32 11 หลายเดือนก่อน +2

      This is taken care of by the heap itself. If you want to get into the weeds with it, the requirements for malloc and the heap to be as efficient as possible while also keeping track of memory properly have created a surprisingly complex design.

  • @obsoquasi
    @obsoquasi 11 หลายเดือนก่อน

    Very concise. Explaining a complex topic with in such a short time I hard! Well done!

    • @PortfolioCourses
      @PortfolioCourses  11 หลายเดือนก่อน

      I’m glad you enjoyed it! :-)

  • @HoSza1
    @HoSza1 11 หลายเดือนก่อน +4

    somehow i expected that the return-the-array-wrapped-in-a-struct technique would also be mentioned, but whatever 😂

  • @doublex85
    @doublex85 11 หลายเดือนก่อน +1

    It's true, C arrays are second class citizens. They decay into pointer-to-first-element if you look at them funny and you cannot pass them into and out of functions. Structures, though, do not have these limitations, so you if you want to have real array values you just have to give their types structure names. C99 even gives you a syntax for them in compound literals.
    typedef struct { int a[5]; } int5;
    int5 map_inc(int5 vals) {
    for (int i = 0; i < 5; i++)
    vals.a[i]++; // vals isn't a pointer, this does not mutate the caller's array.
    return vals; // return the whole array as one value.
    }
    int main(void) {
    int5 inced = map_inc((int5){ .a = {1,2,3,4,5} });
    return inced.a[4]; // exit code 6.
    }

  • @ejimenez1588
    @ejimenez1588 ปีที่แล้ว +38

    I needed this video 😭 strings and arrays in C are killing me

    • @kalpeshlakum852
      @kalpeshlakum852 11 หลายเดือนก่อน +6

      Just clear your pointer knowledge and pointer arithmetics it will be easy to understand.

    • @jacksonlevine9236
      @jacksonlevine9236 11 หลายเดือนก่อน

      Pointer to the beginning of a block of memory on the heap or the stack! (Stack is cleared at end of function, so use heap if you need it to last longer)

    • @markcbaker
      @markcbaker 11 หลายเดือนก่อน +3

      Always remember you need one extra byte for strings. Having the null terminator falling off the end of the char array, is a cause of many bugs.

  • @johndubchak
    @johndubchak 7 หลายเดือนก่อน

    I love these videos. Great content, and beautiful explanations. The only nit I have is where the pointer indicator is...I always read it as the dereference operator when it is next to the name of the thing it refers to. (Sorry, don't flame me)

  • @emblink27
    @emblink27 11 หลายเดือนก่อน

    I clicked the video because the first thought was “wait a minute, is it possible in C?”
    And as I thought it’s not 😊
    The explanation was great, I think it worth to mention that array can be encapsulated in a struct or union, and those can be returned directly.

    • @PortfolioCourses
      @PortfolioCourses  11 หลายเดือนก่อน

      That's a good point re: encapsulating an array in a struct or union, do you know if there is a "known" use case for that? Maybe I could cover it in a video as a "coding trick" sort of thing, but I don't know if there is an actual situation where that's advised, maybe if it's a small array or known size that's attached to other relevant data in the struct?

    • @emblink27
      @emblink27 11 หลายเดือนก่อน

      ​@@PortfolioCourses It's no frequently used, but if you want to return more then one argument from the function (maybe including small array) without passing a bunch of pointers to the input the struct is an ideal solution. And for the array encapsulation, I usually use this trick in embedded systems. For example, I have an SPI bus witch sends some defined packets with a known maximum size. Those packets are described as a union witch contains different structs (packet types), and a uint8_t rawdata[PACKET_MAX_SIZE] array. When I receive bytes from SPI, I store them in the union array and when the transfer is finished I return a union packet which is easily processed by the packet parser. So I'm still returning a union but it was filled like an array. Hope this brief explanation makes sence)

    • @emblink27
      @emblink27 11 หลายเดือนก่อน

      @@PortfolioCourses I think the best use case for struct is when you need to return a multiple variables from a function, maybe including a relatively small fixed size array, without passing a bunch of pointers to the function input.

    • @emblink27
      @emblink27 11 หลายเดือนก่อน

      @@PortfolioCourses As for the unions, I like to use them with arrays in embedded systems because it’s really useful in some cases. For example I have 2 microcontrollers talking to each other by SPI bus. The packets maximum size is known, they are represented as a union which contains a bunch of structs (each struct represent different packet type) and one array of uint8_t data[PACKET_MAX_SIZE]. SPI HAL stores received bytes in union data array. When the SPI transfer is finished, the SPI HAL returns a union which is already filled with bytes and can be processed very quickly be the packet processor.
      Hope this explanation makes some sense 🙂

  • @renzcarlosalanga6077
    @renzcarlosalanga6077 5 หลายเดือนก่อน

    Very good explanation

  • @X_Baron
    @X_Baron 11 หลายเดือนก่อน

    A side note: you don't actually need to manually free any memory when the program ends, because the operating system will do it for you. You should free any allocated, unneeded memory if you intend to keep the program running, or possibly just to keep things consistent and avoid memory leak warnings.

  • @charlesabju907
    @charlesabju907 11 หลายเดือนก่อน +1

    This video is a great example of why you should start learning to program by learning C.

    • @PortfolioCourses
      @PortfolioCourses  11 หลายเดือนก่อน +1

      It definitely forces you to learn in a certain way, other languages can feel easier afterwards... like learning to drive manual before learning to drive automatic. :-)

  • @juanmacias5922
    @juanmacias5922 2 ปีที่แล้ว +2

    Thanks for the video! This can be a struggle lol

  • @Dom-zy1qy
    @Dom-zy1qy 11 หลายเดือนก่อน

    Part of me despises pointer arithmetic, part of me appreciates it

  • @MrHasenfeffer
    @MrHasenfeffer 11 หลายเดือนก่อน

    Note that there is only one copy of that static variable. So everytime set_array(...) Is called, every reference to the array will see the values change since they all point to the same memory location.

  • @LetTheColorSpeak
    @LetTheColorSpeak 11 หลายเดือนก่อน

    This video help me so much! Thank you❤

  • @borkbork4286
    @borkbork4286 11 หลายเดือนก่อน

    THANKU SO MUCH, ur videos r soo clear! :)

  • @davannaleah
    @davannaleah 11 หลายเดือนก่อน

    another way would be to pass the address of the array as a parameter to the function (it would be another function, not main). The problem with this though is that you must make sure the array is large enough for the function, in this case it must be length of 5 ints.

  • @stephenholland6328
    @stephenholland6328 10 หลายเดือนก่อน

    Could you define the function “int array[5] myfunction(void)” ? I mean, no compiler could put an array of unknown size on the stack to return. However, a fixed size array is another matter. After all, c will let you return a struct.

  • @xealit
    @xealit 11 หลายเดือนก่อน +1

    What if you return a struct with a known size array inside?

    • @PortfolioCourses
      @PortfolioCourses  11 หลายเดือนก่อน +1

      That can work but it’s not a recommended method, I may cover that in another video as a “coding trick”. :-)

  • @mongraal2272
    @mongraal2272 2 ปีที่แล้ว +2

    sir,can u please do a video about how triple loops work...im so confused and i cant find anything on the internet

    • @PortfolioCourses
      @PortfolioCourses  2 ปีที่แล้ว +2

      Like a loop inside a loop inside a loop? OK, I've added that to my list of ideas. That said, generally speaking we try to avoid doing that because it usually means the code may be inefficient because all the repetition has a "multiplicative effect". Sometimes we can't avoid it though. This video on matrix multiplication uses a triple loop: th-cam.com/video/G_WjTIBTMhY/w-d-xo.html. :-)

  • @JavSusLar
    @JavSusLar 11 หลายเดือนก่อน +1

    Are Static variables located at the STACK or at the HEAP?

    • @somedude-tr1mj
      @somedude-tr1mj 11 หลายเดือนก่อน +2

      Neither. Static variables, whether declared within functions or at global scope of a particular source file, sit at a fixed address (determined at link and/or load time) within the process, that's neither in the stack nor the heap.

  • @rifatfatma6373
    @rifatfatma6373 14 วันที่ผ่านมา

    We can return locally created array if we declare static array
    static int arr_local[5];

  • @zoquevil4792
    @zoquevil4792 2 ปีที่แล้ว +2

    Great video as always!!!
    Could we say it also possible with a global variable like the example you give with the static one?

    • @PortfolioCourses
      @PortfolioCourses  2 ปีที่แล้ว +2

      Yes, I suppose we could do it that way, but I wouldn't recommend it, and we would want to be very, very careful about how we use that array since it is global and any function can access it. 🙂

  • @Klinifini
    @Klinifini 10 หลายเดือนก่อน

    How does free know what size of the memory needs to be released?

  • @Tech-Relief
    @Tech-Relief 11 หลายเดือนก่อน

    As an old retired software engineer I have always shunned C and C++ because they suck. However, with Arduino etc. I am stuck using it, but I disagree with your view of static variables, I would always recommend using some sort of global variable in preference of Malloc and free. In your example the malloc is in a function and the free is outside of it, that is bad. I would set a rule that any malloc should have a matching free in the same function or method to avoid a programmer forgetting to free and create a memory leak.

  • @yolamontalvan9502
    @yolamontalvan9502 ปีที่แล้ว

    Could you make a video using a 2D array. I have problems passing a 2D-array to a function and returning modified.
    Your tutorials are so clear and easy to understand. Thank you.

    • @yolamontalvan9502
      @yolamontalvan9502 ปีที่แล้ว

      I think you already did that. I’ll check it out.

  • @crispytek6783
    @crispytek6783 ปีที่แล้ว

    Thank you ever so much, really appreciate it!

  • @jbergamot
    @jbergamot 11 หลายเดือนก่อน

    What is your IDE, environment? Thanks

  • @miricledev
    @miricledev ปีที่แล้ว

    VERY HELPFUL thank you

  • @Videoman2102
    @Videoman2102 ปีที่แล้ว

    In C compiler online in "onlinegdb" says error: conflicting types for ‘set_array’; have ‘int *(int)’

    • @PortfolioCourses
      @PortfolioCourses  ปีที่แล้ว

      Hmm that's odd Mario... the original source code is posted here: github.com/portfoliocourses/c-example-code/blob/main/return_an_array.c. When I copy and paste that into onlinegdb, I do not get any errors.

  • @abyssalblackdragon6667
    @abyssalblackdragon6667 16 วันที่ผ่านมา

    does anybody know what c compiler is this

  • @jnarical
    @jnarical 11 หลายเดือนก่อน

    What do I do if I need to return an array of a variable size? Defining its size in runtime. I mean, if I want it on a stack. Is there ways to do that?

    • @psyience3213
      @psyience3213 11 หลายเดือนก่อน

      arrays on the stack need to have their size known at compile time.

    • @jnarical
      @jnarical 11 หลายเดือนก่อน

      @@psyience3213 I know. But there should be workarounds. Modern C++ has some tricks for that, I’m sure

    • @jnarical
      @jnarical 11 หลายเดือนก่อน

      @@psyience3213 there’s a high frequency function. It uses C-style array for speed. Usually the size of it is somewhere between 80 and 161, but sometimes it’s 480.
      I can use other ways to optimise that, but that would hit code readability, and honestly there’s no necessity… so if there ways to make C-style arrays more dynamic I’m looking for it )
      For now, I’m using static array of size 480 for all cases, getting rid of reallocation but wasting almost 80% of its size most of the time

    • @psyience3213
      @psyience3213 11 หลายเดือนก่อน +1

      @@jnarical those are basically your only other options as far arrays. Otherwise you can use other data structures but arrays are the fastest. If you're not resizing and moving stuff you can do something like a linked list of arrays where each link contains an array of 80 elements and you add links as you need more.

    • @jnarical
      @jnarical 11 หลายเดือนก่อน

      @@psyience3213 Smart.

  • @Mnogojazyk
    @Mnogojazyk ปีที่แล้ว

    What do you do when a function does not know the number of elements in an array? As far as I know, C doesn’t have a general array length() function call, e.g., the static variable .length in Java.
    Does the programmer have to keep track of the array’s element count in the calling function and pass to the called function the count? Example:
    int *set_array(int value, int count)
    {
    Int *array = malloc(sizeof(int) * count) ;
    for (i = 0 ; i < count ; i+)
    array[i] = value ;
    return array ;
    }

    • @PortfolioCourses
      @PortfolioCourses  ปีที่แล้ว +4

      Yes, that's basically the idea. When we pass an array to a function, what really gets passed is the memory address of the first element in the array, not the entire array. So we need the function to know "somehow" how big the array is... maybe we pass the length as an argument, maybe it's a preprocessor constant or hard-coded value, etc.

    • @Mnogojazyk
      @Mnogojazyk ปีที่แล้ว +1

      @@PortfolioCourses, acknowledged. Thanks for the confirmation.

    • @PortfolioCourses
      @PortfolioCourses  ปีที่แล้ว +2

      You're welcome! :-)

  • @SirKenchalot
    @SirKenchalot 11 หลายเดือนก่อน

    You hardcoded the length of the array each time. What is the length isn't known at compile time?

    • @psyience3213
      @psyience3213 11 หลายเดือนก่อน

      you can dynamically allocate arrays with variable size. int* ptr = malloc(sizof(int) * sizeOfArray); That's the point of dynamic allocation

  • @muhisaleh4598
    @muhisaleh4598 2 ปีที่แล้ว +1

    thnx for this great video!!!
    i just have one question, if we have a Funktion that return a pointer to an (int)array, how can we find the size of that returned array in the main fun?
    int* containDigits(int number []){//////function the returned pointer to a new array
    return new;
    }
    int main{
    int numbers[] = {4213,132,43};
    int n =0;
    int *numbers1 =containDigits(numbers);//////////also here how can we find size of the array

    return 0;
    }

    • @PortfolioCourses
      @PortfolioCourses  2 ปีที่แล้ว

      That's a great question Muhi. :-) And the answer is that we can't really find the size of the array in the main function. If it were an array on the stack, we could use sizeof, like in this video: th-cam.com/video/ZCzXhRkiBu4/w-d-xo.html. But that isn't going to help us here. What we could do though is use pass-by-reference, also called pass-by-pointer in C, to return the length of the array: th-cam.com/video/RecxQUUEOn4/w-d-xo.html. Pass-by-reference will essentially allow us to return multiple things from an array in C. :-)

    • @muhisaleh4598
      @muhisaleh4598 2 ปีที่แล้ว +1

      @@PortfolioCourses thank you very much for your help!!

    • @PortfolioCourses
      @PortfolioCourses  2 ปีที่แล้ว +1

      You're welcome! :-)

  • @snygg1993
    @snygg1993 10 หลายเดือนก่อน

    You might have a memory leak despite using "free".
    Since "result" is a "int*" I would assume the call "free(result)" will free 1 int instead of 5?
    And wouldn't it be better to handle malloc and free in one scope, since spreading the handling of memory over multiple functions/scopes makes it hard to track and thus almost guaranties memory leaks.

    • @PortfolioCourses
      @PortfolioCourses  10 หลายเดือนก่อน

      No we won’t have a memory leak by calling free() this way. And no, we do not need to handle allocation and freeing in the same scope, it does not “guarantee” memory leaks. I know some teachers will teach students to do it that way, but real C programs just don’t work that way. Data structures like linked lists and binary search trees depend on not allocating in the same scope/functions.

    • @snygg1993
      @snygg1993 10 หลายเดือนก่อน

      @@PortfolioCoursesok, interesting.
      What I still dont understand is how does free() know the size to be freed? Does malloc() maintain a list of all created pointers to know their respective allocated size?

  • @wesleytaylor-rendal5648
    @wesleytaylor-rendal5648 2 ปีที่แล้ว

    I use vscode, can i get an error warning extension that is as good as yours?

    • @PortfolioCourses
      @PortfolioCourses  2 ปีที่แล้ว +1

      Great question Wesley. 🙂 I'm not sure if it would be the same as Xcode in terms of the warnings provided, but I'd try these as a starting point: marketplace.visualstudio.com/items?itemName=ms-vscode.cpptools-extension-pack. When I'm not using Xcode, I've always just used a terminal running gcc as a matter of preference, and I've found the warnings gcc gives me to be pretty good too.

  • @heshamelnabtity2830
    @heshamelnabtity2830 2 ปีที่แล้ว

    Good work, thanks

    • @PortfolioCourses
      @PortfolioCourses  2 ปีที่แล้ว +1

      You're welcome Hesham, I'm glad you enjoyed it! :-)

  • @undersquire
    @undersquire 11 หลายเดือนก่อน

    You can still return an array directly from a function in C by wrapping the array into a custom struct declaration, although it's a bit verbose.

    • @PortfolioCourses
      @PortfolioCourses  11 หลายเดือนก่อน +1

      It’s inefficient too due to the copying of the struct that happens, I’ve thought of doing a video on this. :-)

    • @undersquire
      @undersquire 11 หลายเดือนก่อน

      @@PortfolioCourses I guess it depends on the context and how it's used, but with compiler optimizations it generates the same (in some cases even simpler) assembly for the struct definition version. But you are right if optimizations are turned off.

    • @PortfolioCourses
      @PortfolioCourses  11 หลายเดือนก่อน +1

      No, even with optimizations turned on, because of the way return values work, you wouldn’t want to do that with anything but a very small array in a struct. Again I might make a video to explain this.

    • @undersquire
      @undersquire 11 หลายเดือนก่อน

      @@PortfolioCourses Right my bad, I didn't specify I was talking about small arrays like in the video, anything remotely big should definitely not be returned by value.

    • @undersquire
      @undersquire 11 หลายเดือนก่อน

      Actually testing this in Godbolt to view the assembly, even with returning an array with 3000 integers the compiler optimizes the assembly to instantiate the array inline and doesn't make a copy, generating nearly identical assembly to a pointer-based implementation (with -O3). I still wouldn't rely on this in real code however, but an interesting experiment.

  • @orisphera
    @orisphera 11 หลายเดือนก่อน

    How does the following work?
    #include
    #include
    int *set_array(int value)
    {
    static int array[5];
    for (int i = 0; i < 5; i++)
    array[i] = value;
    return array;
    }
    int main()
    {
    int *a1 = set_array(1);
    int *a2 = set_array(2);
    printf("%i", a1[1]); // outputs 1
    }
    It's hard for me to formulate my question. If you see what it may be, what's the answer?

  • @knowledgeofinvesting8872
    @knowledgeofinvesting8872 2 ปีที่แล้ว

    are you doing this on mac if so which ide is it?

    • @PortfolioCourses
      @PortfolioCourses  2 ปีที่แล้ว

      Yes, and in this video I am using Xcode. :-)

  • @AlMiCo86
    @AlMiCo86 11 หลายเดือนก่อน

    I would prefer to name the function argument „array“ different from main, just to make exactly clear what is going on. Might be mixed up by beginners.

  • @ritankarmondal8707
    @ritankarmondal8707 6 หลายเดือนก่อน

    what is the ide used in the video?

  • @doruk5766
    @doruk5766 ปีที่แล้ว

    I did the way you did first time and my program worked perfectly even thought it gave an error on yours. Does anyone have any idea why would that be?

    • @johnshaw6702
      @johnshaw6702 11 หลายเดือนก่อน +1

      The data was still there, because it wasn't overwritten in memory yet. When the function returns it basically pops all local variables off the stack. That is the memory where they were stored is no longer reserved for them. That memory can be overwritten before you try to access it and is therefore considered undefined.
      If you took the address returned and immediately access it, then there is a good chance the data that was stored there hasn't change yet. But, if you do anything in your program before attempting to access it, then you probably overwrote that memory location and the original data stored there is gone.
      I hope that helps. It would be easier to explain with a diagram, but you should get the idea.

    • @doruk5766
      @doruk5766 11 หลายเดือนก่อน +1

      @@johnshaw6702 Thank you very much for taking the time to answer properly, I understand now.

  • @kcvinu
    @kcvinu 11 หลายเดือนก่อน

    Why don't you use calloc instead of malloc ?

    • @PortfolioCourses
      @PortfolioCourses  11 หลายเดือนก่อน +1

      This video explains the differences between the two functions: th-cam.com/video/SKBnxCq3HvM/w-d-xo.html

    • @kcvinu
      @kcvinu 11 หลายเดือนก่อน

      @@PortfolioCourses Thanks. Let me watch it.

  • @loldart
    @loldart 2 ปีที่แล้ว +1

    Was very helpful when understanding on to setup arrays!

    • @PortfolioCourses
      @PortfolioCourses  2 ปีที่แล้ว +1

      I’m glad to hear it was helpful Jack! :-)

    • @loldart
      @loldart 2 ปีที่แล้ว

      @@PortfolioCourses I do have a follow up question. Do you have a video on strings with spaces in C coding? I been stuck on that one for a few days.

    • @PortfolioCourses
      @PortfolioCourses  2 ปีที่แล้ว +1

      As in user input with spaces? If so, this video might help you out: th-cam.com/video/f8589Y9LHHg/w-d-xo.html. :-)

    • @loldart
      @loldart 2 ปีที่แล้ว

      @@PortfolioCourses Much appreciated! Will take a look after work!

    • @PortfolioCourses
      @PortfolioCourses  2 ปีที่แล้ว

      @@loldart You're welcome Jack! 🙂

  • @andsoehd277
    @andsoehd277 11 หลายเดือนก่อน

    what different between array and &array?

    • @PortfolioCourses
      @PortfolioCourses  11 หลายเดือนก่อน

      This video covers that: th-cam.com/video/WL1P6xiA_KY/w-d-xo.html. :-)

    • @andsoehd277
      @andsoehd277 11 หลายเดือนก่อน

      @@PortfolioCourses thank you! :D

  • @DatBoi_TheGudBIAS
    @DatBoi_TheGudBIAS 11 หลายเดือนก่อน

    If the array is 8 bytes of ints or 16 bytes of floats or doubles, technically it's possible, but C probably just denies it all

  • @about2mount
    @about2mount 11 หลายเดือนก่อน

    We never do this in Programming we instead send an array to a void functuion as a reference then change it and we are done.
    If you going to teach how arrays can be passed to functions then don't. We have no need to ever return them because the function is assigned to the actual array being passed. So even though the array inside the function has a different name it still holds reference to the outside array.
    So how does it reference the outside array? The function itself accepts the outside array in the following example asa reference because of these" [ ]". So there is no need for a reference or a pointer ever.
    #include
    #include
    #include
    using namespace std;
    int count=0;
    void asn_new_val(int ar[], int val){
    ar[count] = val;
    count++; //auto increments the counter
    };
    void re_assign_array(int ar[], int cnt, int new_value) {
    ar[cnt] = new_value;
    };
    void print_array(int ar[]){
    cout

    • @PortfolioCourses
      @PortfolioCourses  11 หลายเดือนก่อน

      Did you watch the video? :-)

  • @piotrprs572
    @piotrprs572 11 หลายเดือนก่อน

    and this is why C is to 'complicated' to many of programmers. 🙂
    Is to close to asm and v. easy you can do something that crash whole program or even system. 😀

    • @PortfolioCourses
      @PortfolioCourses  11 หลายเดือนก่อน

      As much as C can frustrate me, I think it's great for students to learn, because it's so close "to the metal". :-)

  • @harithabandara3212
    @harithabandara3212 ปีที่แล้ว

    Thank you❤

  • @peligros13
    @peligros13 11 หลายเดือนก่อน

    No, never do that with the static keyword in this scenario. If you call the function a second time, it will mess up your array instead of giving you another one.

  • @mohamedanoof102
    @mohamedanoof102 2 ปีที่แล้ว

    Thank you so much

  • @tamptus3479
    @tamptus3479 10 หลายเดือนก่อน +1

    If you want to return an array by value, you have to put it in a struct.

  • @aghiadalzein3069
    @aghiadalzein3069 10 หลายเดือนก่อน

    Great Explanation thanks.

    • @PortfolioCourses
      @PortfolioCourses  10 หลายเดือนก่อน

      You're welcome, I'm glad you enjoyed it! :-)

  • @lakshaygupta4786
    @lakshaygupta4786 2 ปีที่แล้ว

    Thanks!!

  • @tinky3110
    @tinky3110 11 หลายเดือนก่อน

    So basically you can't return a classic array.

  • @orisphera
    @orisphera 11 หลายเดือนก่อน

    I'd try
    int[5] my_function() {...}

  • @unixux
    @unixux 11 หลายเดือนก่อน

    You should’ve actually returned a pointer to an array instead ( int p[]; return &p ) . Instead of casting array to pointer

    • @PortfolioCourses
      @PortfolioCourses  11 หลายเดือนก่อน

      In C an array “decays to a pointer”.

  • @brkvrlgl2997
    @brkvrlgl2997 2 ปีที่แล้ว

    ı am a rookie and ı am so confused :(

    • @PortfolioCourses
      @PortfolioCourses  2 ปีที่แล้ว +1

      Returning arrays from a function is definitely more of an advanced topic in C. Especially if we use dynamic memory allocation. These videos might help you out in terms of understanding related concepts. :-)
      Introduction to Pointers: th-cam.com/video/2GDiXG5RfNE/w-d-xo.html
      Dynamic Memory Allocation: th-cam.com/video/R0qIYWo8igs/w-d-xo.html
      Passing An Array To A Function: th-cam.com/video/oe2bZKjiWrg/w-d-xo.html

    • @brkvrlgl2997
      @brkvrlgl2997 2 ปีที่แล้ว +1

      @@PortfolioCourses wow thank you for your interest ı will look them

    • @PortfolioCourses
      @PortfolioCourses  2 ปีที่แล้ว +1

      @@brkvrlgl2997 You're welcome. 🙂

  • @aknsagdic9388
    @aknsagdic9388 6 หลายเดือนก่อน

    Great

  • @adnanemezrag3809
    @adnanemezrag3809 2 ปีที่แล้ว

    is so complicated though

    • @PortfolioCourses
      @PortfolioCourses  2 ปีที่แล้ว

      You're right... I prefer Python and other languages where this sort of thing is easier. :-)

  • @piotrprs572
    @piotrprs572 11 หลายเดือนก่อน

    btw.. this example sucks in every way. You shouldn't do such thing like malloc outside you main function. Is only one exeption, that you create special function to 'initate' program and another to 'close' all handlers.
    Example should show, that we do malloc inside main function, thet we pass pointer of this array to subfunction.

    • @PortfolioCourses
      @PortfolioCourses  11 หลายเดือนก่อน

      I know sometimes teachers tell their students to do those things to have them prevent memory leaks, but that's not actually how real C programs work. If we create something like a data structure (linked list, binary search trees) that's not going to work out trying to use malloc only in main(), we need to be able to call functions to create new nodes and other functions to remove them. Also, see this example of using malloc() outside of main in Linux: github.com/torvalds/linux/blob/7e90b5c295ec1e47c8ad865429f046970c549a66/tools/perf/jvmti/libjvmti.c#L195. There are many other examples of this: github.com/search?q=repo%3Atorvalds%2Flinux+%22+malloc%28%22&type=code.

  • @divinechijindu7465
    @divinechijindu7465 10 หลายเดือนก่อน

    Who else heard those kids in the background 😂😂

  • @QuikRay
    @QuikRay 11 หลายเดือนก่อน

    Return by reference, not by value.much quicker

  • @gloubiboulgazeblob
    @gloubiboulgazeblob 10 หลายเดือนก่อน

    Well explained, but correct me if I'm wrong : this is ok for static arrays (size never changes), but it becomes more tricky with dynamic arrays, their size is unknown to a function that is called...Giving their size as well when calling a function would be the only solution ?
    See : th-cam.com/video/6Ir4l0VuI7Y/w-d-xo.html