I have the following function in C:
int[] function(int a){ int * var = (int*)malloc(sizeof(int)*tags); .... }
*varis a pointer to an array var?
*var
var
If so, how do I return an array ( var) to a function?
You cannot return an array from a function, but a pointer:
int * function(int a){ int * var = malloc(sizeof(int)*tags); //.... return var; }
This code below may clarify a bit how arrays and pointers work. The function will allocate memory for the "tags" of int variables, then initialize each element with a number and return a memory segment that points to an array. From the main function, we will cyclically print an array element, then we will free up unnecessary memory.
#include <stdio.h> #include <stdlib.h> int *function(unsigned int tags) { int i; int *var = malloc(sizeof(int)*tags); for (i=0; i < tags; i++) { var[i] = i; } return var; } int main() { int *x; int i; x = function(10); for (i=0; i < 10; i++) { printf("TEST: %i\n", x[i]); } free(x); x=NULL; return 0; }
:
int* function(int tags){ int * var = malloc(sizeof(int)*tags); //.... return var; }
( ) C/++, , .
: a, tags . ,
a
tags
, free() , function , , . malloc tags int s, int var[tags];
free()
function
malloc
int
int var[tags];
UPDATE: malloc return
C . int:
int *function(int a) { int *var = malloc(sizeof *var * tags); // where is tags defined? // are you sure you don't mean a here? ... return var; }
, tags integer var. , var int, int. , .
, , :
int a = ...; int *arr = function(a); ... arr[0] = 0; arr[1] = 1; ...
arr - , , sizeof arr , , (- , ).
arr
sizeof arr
C , . , char [] char *
Remember to keep track of the size of the array, also I noticed that tags seem to be a global variable, most of the time it is a good idea to avoid global variables
Here is a sample code:
#include <stdio.h> #include <stdlib.h> int* foo(size_t arrSize){ int* arr = (int*) malloc(sizeof(int)*arrSize); return arr; } int main (int argc, char** argv){ printf("Printing array:\n"); int* arr = foo(42); for(int i=0; i <42; i++){ arr[i]=i; } for (int i=0; i < 42; i++){ printf("Element: %d: %d\n", i, arr[i]); } free(arr); return 0; }