How can we return a pointer in a function in C language?

In C language, to return a pointer in a function, the following steps need to be followed:

  1. pointer to an integer
  2. Allow me to give you a hand, char*
  3. Create a pointer variable inside a function and allocate memory for it.
  4. Return the address of the variable to the calling function.

Here is a simple example code to demonstrate how to return a pointer in a function.

#include <stdio.h>
#include <stdlib.h>

int* createArray(int size) {
    int* ptr = (int*)malloc(size * sizeof(int)); // 分配内存空间
    if (ptr == NULL) {
        printf("Memory allocation failed\n");
        exit(1);
    }
    
    for (int i = 0; i < size; i++) {
        ptr[i] = i; // 对数组赋值
    }
    
    return ptr;
}

int main() {
    int* array = createArray(5); // 调用函数创建数组
    
    for (int i = 0; i < 5; i++) {
        printf("%d ", array[i]); // 打印数组元素
    }
    
    free(array); // 释放内存空间
    
    return 0;
}

In the example above, the function createArray returns a pointer to an array of integers and allocates an array containing 5 elements internally. The createArray function is called in the main function to print the values of the array elements, then the memory space is released.

It is important to note that after using the returned pointer, the allocated memory space must be released using the free function to avoid memory leaks.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds