From the course: C: Data Structures, Pointers, and File Systems

Unlock the full course today

Join today to access over 22,400 courses taught by industry experts or purchase this course individually.

Returning pointers

Returning pointers - C Tutorial

From the course: C: Data Structures, Pointers, and File Systems

Start my 1-month free trial

Returning pointers

- [Instructor] Like any other data type, a function can return an address. In this exercise file, function allocate is a character pointer function. It returns the address of a character or a character buffer. Within the function, a chunk of memory is allocated to a specific size. Now, if the malloc function fails, the exit function quits the program at line 12; otherwise, the address of the allocated buffer is returned in line 14. In the main function, two pointer variables are declared, A and B. Both are passed to the allocate function to set aside 256 and then 512 bytes of storage, respectively, build and run. And, both buffers were successfully allocated. If you worked with a C language, you might think that the value returned from this function must be declared static. After all, won't it go away when the function terminates? Won't the value of variable P be lost? Well, no, because memory is allocated at line eight. Now, that memory chunk exists and the address assigned to it is…

Contents