【发布时间】:2010-09-15 07:37:29
【问题描述】:
我正在尝试使用以下结构实现环形缓冲区
/*head, tail are indexes of the head and tail of ring buffer
*count is the number of elements; size is the max size of buffer
*rbArray is an array to pointer of char used to store strings
*/
struct rb{
int head;
int tail;
int count;
int size;
char *rbArray[];
};
然后我使用下面的函数来创建一个字符串缓冲区:
struct rb *create(int n){
/*allocate memory for struct*/
struct rb *newRb = (struct rb*)malloc(sizeof(struct rb)+ n*sizeof(char *));
assert(newRb);
int i;
for(i=0;i<n;i++)
newRb->rbArray[i] = NULL;
/*put head and tail at the beginning of array
initialize count, set max number of elements*/
newRb->head = 0;
newRb->tail = 0;
newRb->count = 0;
newRb->size = n;
return newRb;
}
我在 main 中调用这个函数:
struct rb *newRB = (struct rb*)create(100);
但是,我在为 struct 分配内存的步骤中遇到了问题。在调试模式下,我可以看到 head、tail、count 的值被分配了非常奇怪的大数字,但不是 0。在第一步之后程序挂起,没有抛出任何异常。
有人可以帮我解释一下这个问题吗?我该如何解决?
【问题讨论】:
-
您的代码看起来不错(并且在我的计算机上运行良好)。我只是删除演员表并将 sizeof 应用于对象而不是类型。
-
"exception" ... 嗯:你是在编译你的代码为
C(不是C++)吗? -
您的代码(有一些不相关的更改)在 ideone 的编译器上运行正常(ideone.com/1QLey)
-
stackoverflow.com/questions/3711233/… - 虽然不是重复的,但绝对值得一看。
-
代码看起来不错,但类型转换看起来有点可疑。 C 代码中不应该需要它们。特别是,如果编译器抱怨您的
struct rb *newRB = create(100);调用中的类型,那么您还有其他一些被类型转换隐藏的问题。
标签: c arrays struct malloc member