C returning a pointer from a function

Source: Internet
Author: User

In the previous chapter, we've learned how to return an array from a function in C, similarly, C allows you to return a pointer from a function. To do this, you must declare a function that returns a pointer, as follows:

1 int * myFunction ()2{3. 4 . 5 . 6 }

In addition, C does not support returning the address of a local variable outside of a function unless the local variable is defined as a static variable.

Now, let's look at the following function, which generates 10 random numbers and returns them using the array name that represents the pointer (that is, the address of the first array element), as follows:

1#include <stdio.h>2#include <time.h>3#include <stdlib.h>4 5 /*function to generate and return a random number*/6 int*getrandom ()7 {8    Static intr[Ten];9    inti;Ten   One    /*Set seed*/ A Srand ((unsigned) time (NULL)); -     for(i =0; I <Ten; ++i) -    { theR[i] =rand (); -printf"%d\n", R[i]); -    } -   +    returnR; - } +   A /*to invoke the main function that defines the function above*/ at intMain () - { -    /*a pointer to an integer*/ -    int*p; -    inti; -  inp =getrandom (); -     for(i =0; I <Ten; i++ ) to    { +printf"* (p + [%d]):%d\n", I, * (P +i)); -    } the   *    return 0; $}

When the above code is compiled and executed, it produces the following results:

1 15231980532 11872141073 11083009784 4304949595 14213012766 9309710847 1232504848 1069321409 1604461820Ten 149169022 One* (P + [0]) :1523198053 A* (P + [1]) :1187214107 -* (P + [2]) :1108300978 -* (P + [3]) :430494959 the* (P + [4]) :1421301276 -* (P + [5]) :930971084 -* (P + [6]) :123250484 -* (P + [7]) :106932140 +* (P + [8]) :1604461820 -* (P + [9]) :149169022

C returning a pointer from a function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.