Kei*_*ler 7 c arrays return function dynamic
所以目前我有一个函数我返回一个静态数组,有没有办法让它返回一个动态数组为了效率?
#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;
}
Run Code Online (Sandbox Code Playgroud)
函数不能返回数组,句点.您当然可以使用指针或指针指向调用者已分配的内存块.所以,在你的情况下......
int *ret = malloc(255 * sizeof int); // caller must deallocate!
Run Code Online (Sandbox Code Playgroud)
但这确实会改变代码的语义.函数的调用者现在负责调用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;
}
}
Run Code Online (Sandbox Code Playgroud)
如果我没有回答你的问题,你需要为我(我们)详细说明.你现在没有返回阵列; 你正在返回一个指向int
静态分配数组的第一个元素的指针.