所以现在我有一个返回静态数组的函数,有没有办法为了提高效率让它返回动态数组呢?
#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;
}发布于 2012-08-01 06:39:44
函数不能返回数组,句号。当然,您可以使用指针,也可以使用指向调用方分配的内存块的指针。所以在你的情况下..。
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的指针,该指针指向静态分配的数组的第一个元素。
发布于 2017-01-31 00:47:04
实际上,使用静态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);
}完美和简单如果你有更多的内存,那么你需要更少的时间(你也需要有点懒惰)。
https://stackoverflow.com/questions/11750050
复制相似问题