Is there a way to get my function to return a dynamic array?

So, at the moment, I have a function that I did, returning a static array, is there any way to make it return a dynamic array for the sake of efficiency?

#include <stdio.h> #include <stdlib.h> #include "header.h" int *charpos(char *str, char ch) { int *bff, bc, ec, i, strln; static int ret[255]; bc = 0; ec = 0; for(i = 0; str[i] != '\0'; i++) ; strln = i; for(i = 0; i <= strln; i++) { if(str[i] == ch) ec++; } bff = malloc(sizeof(int)*ec); if(sizeof(bff) > sizeof(ret)) { free(bff); return 0; } for(i = 0; i <= 255; i++) ret[i] = '\0'; for(i = 0; i <= strln; i++) { if(str[i] == ch) { ret[bc] = i; bc++; } } free(bff); return ret; } 
+6
source share
2 answers

Functions cannot return arrays, period. You can, of course, a pointer or take a pointer to a block of memory that has been allocated by the caller. So in your case ...

 int *ret = malloc(255 * sizeof int); // caller must deallocate! 

However, this changes the semantics of your code. The subscriber of your function is now responsible for calling free() on the returned pointer. If they do not, you will have a memory leak, so this will add some complexity that was not there before. Instead, I would prefer something like this:

 void charpos(int *p, size_t size, const char *str, char ch) { // initialize the memory memset(p, 0, size * sizeof int); // your other code here... size_t len = strlen(str); // fill the caller memory for(i = 0; i < len; ++i) { if(str[i] == ch) p[bc++] = i; } } 

If I did not answer your question, you need to clarify for me (us). You are not returning an array right now; you return a pointer to an int that refers to the first element of a statically allocated array.

+5
source

In fact, you can allocate more space, and then you need a static int, and you don't have to worry about the dynamics. Here's how I solved it:

 //indefinite reads, actually only up to 20 int * readDataAD7142(int addr, int numRegs){ static int data[20]; int i = 0; //Do something with this data array. Something that requires less then 20 elements return data; } 

Here is the code that calls it

  int *p; int i; p = readDataAD7142(0x0000, 6); for(i=0; i<6; i++){ Serial.println(p[i], HEX); } 

Ideal and easy, if you have more memory, then you need a little time (you also need to be a little lazy).

0
source

Source: https://habr.com/ru/post/921806/


All Articles