【发布时间】:2014-07-10 15:12:03
【问题描述】:
所以,我正在做这个练习:
写一个C函数void出现(char* s, char c, char*** occp, int* n) ,给定一个字符串 s 和一个字符 c,计算 在字符串 s 中出现 char c,在 n 中返回该数字并在 occp 中返回包含每个 c 的地址的新 char 数组的地址 发生在s
主要样本:
#include <stdio.h>
int main(){
int i, n;
char** occ;
occorrenze("engineering", 'n', &occ, &n);
for (i=0; i<n; ++i) printf("%s\n", occ[i]); // prints ngineering neering ng
free(occ);
}
一开始我是这样写函数的:
void occurrences(char* s1, char c, char*** s, int* n){
*n=0;
char* arr[2];
int length=strlen(s1);
int i;
for(i=0; i<length; i++){
if(s1[i]==c)(*n)++;
}
*s=(malloc((*n)*sizeof(char**)));
int a=0;
for(i=0; i<length; i++){
if(s1[i]==c){
(*s)[a]= &s1[i];
a++;
}
}
}
工作得很好,但我想尝试重新编写它,只迭代一次字符串。我想过使用 realloc(),这是我以前从未使用过的函数,最终我想出了这个:
void occurrences(char* s1, char c, char*** s, int* n){
*n=0;
*s=malloc(0);
char* arr[2];
int length=strlen(s1);
int i,a=0;
for(i=0; i<length; i++){
if(s1[i]==c){
(*n)++;
*s=realloc(*s,(*n)*sizeof(char**));
(*s)[a]= &s1[i];
a++;
}
}
}
这个似乎也很好用,但后来我运行 Valgrind:
==4893== HEAP SUMMARY:
==4893== in use at exit: 0 bytes in 0 blocks
==4893== total heap usage: 4 allocs, 4 frees, 48 bytes allocated
==4893==
==4893== All heap blocks were freed -- no leaks are possible
==4893==
==4893== For counts of detected and suppressed errors, rerun with: -v
==4893== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 2 from 2)
分配了 48 个字节?它应该是 24 字节,对吧? 总堆大小为 8*n!而不是 8*n... 我想我错过了一些东西 XD
编辑:复制了正确的函数 lol
【问题讨论】:
-
为什么你认为应该是 24 ?
-
@Andrew Medico 复制/粘贴错误,抱歉!
-
32 位还是 64 位系统? 64 位系统使用 8 字节指针,这将使 48。
-
这不会改变这里的结果,但从技术上讲,您应该分配
(*n)*sizeof(char*)字节(不使用sizeof(char**))。 -
@user2482551:感谢您的解释!顺便说一句,我并没有试图让这个功能更高效,我只是在“试验”:)
标签: c memory heap-memory realloc