[英]Is there any way to make my function return a dynamic array?
所以目前我有一個返回靜態數組的函數,為了效率,有沒有辦法讓它返回一個動態數組?
#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;
}
函數不能返回數組,句號。 您當然可以使用指針或獲取指向調用者分配的內存塊的指針。 所以,在你的情況下...
int *ret = malloc(255 * sizeof int); // caller must deallocate!
但是,這確實會更改代碼的語義。 您的函數的調用者現在負責在返回的指針上調用free()
。 如果他們不這樣做,您將泄漏內存,因此這會增加一些以前不存在的復雜性。 我更喜歡這樣的東西:
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's memory
for(i = 0; i < len; ++i)
{
if(str[i] == ch)
p[bc++] = i;
}
}
您正在返回一個指向int
的指針,該指針指向靜態分配的數組的第一個元素。
實際上,您可以使用靜態 int 分配更多空間,而不必擔心動態。 這是我解決它的方法:
//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;
}
這是調用它的代碼
int *p;
int i;
p = readDataAD7142(0x0000, 6);
for(i=0; i<6; i++){
Serial.println(p[i], HEX);
}
如果您有更多的內存和更少的時間(您也需要有點懶惰),那就完美而簡單了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.