dan*_*ani 0 c pointers function
我想将缓冲区和缓冲区长度的指针传递给其他函数,然后使用此数据进行操作并打印它.但是当我尝试在功能上打印它是不可能的.
这是我的代码的一部分:
void process(KOCTET**bufferlist,KUINT16*lenlist){
KOCTET * Buffer,*temp;
KUINT16 BufferSize=5000;
KUINT16 WritePos=0;
KUINT16 total_bytes;
Buffer=(KOCTET*)malloc(5000*sizeof(KOCTET));
total_bytes = stream.CopyIntoBuffer( Buffer, BufferSize, WritePos);
bufferlist=(KOCTET**)malloc(sizeof(KOCTET*));
bufferlist=&Buffer;
lenlist=(KUINT16*)malloc(sizeof(KUINT16));
lenlist=&total_bytes;
//Print Buffer in Hexadecimal
int z=0;
temp=Buffer;
while (z<total_bytes){
printf(" %02X",(unsigned char)*temp);
temp++;
z++;
}
printf("\n");
}
void function ()
{
KOCTET**bufferlist;
KUINT16*lenlist;
process(bufferlist,lenlist);
//Print Buffer in Hexadecimal
int z=0;
temp=*bufferlist;
while (z<(*lenlist)){
printf(" %02X",(unsigned char)*temp);
temp++;
z++;
}
printf("\n");
}
Run Code Online (Sandbox Code Playgroud)
谢谢,
以下几行有几个问题:
bufferlist=(KOCTET**)malloc(sizeof(KOCTET*));
bufferlist=&Buffer;
lenlist=(KUINT16*)malloc(sizeof(KUINT16));
lenlist=&total_bytes;
Run Code Online (Sandbox Code Playgroud)
前两个分配内存,然后使用指向局部变量的指针覆盖指针,该函数在函数返回时无效.接下来的两行相同.所以在这四行中你有两个内存泄漏(分配内存然后更改指向该内存的指针,因此它不再可用)以及当你将指针设置为指向堆栈中仅在内部有效的位置时导致未定义行为的原因功能.
要解决这些问题,请更改为以下内容:
*bufferlist = Buffer;
*lenlist = total_bytes;
Run Code Online (Sandbox Code Playgroud)
编辑:我还注意到你正在调用此函数错误:
KOCTET**bufferlist;
KUINT16*lenlist;
process(bufferlist,lenlist);
Run Code Online (Sandbox Code Playgroud)
这应该改为:
KOCTET *bufferlist;
KUINT16 lenlist;
process(&bufferlist, &lenlist);
Run Code Online (Sandbox Code Playgroud)
这将变量声明为指向KOCTET和a 的指针KUINT16.然后传递这些变量的地址process,这使得它们的指针(即指向指针KOCTET中的情况下bufferlist,并且指针KUINT16在的情况下lenlist).
现在您不需要lenlist在循环中使用解除引用:
while (z < lenlist) {
printf(" %02X", (unsigned char) *temp);
temp++;
z++;
}
Run Code Online (Sandbox Code Playgroud)
现在可以将此循环实际重写为:
for (z = 0; z < lenlist; z++)
printf(" %02X", (unsigned char) bufferlist[z]);
Run Code Online (Sandbox Code Playgroud)
编辑2:解释指针和指针运算符(我希望)
让我们来看看这个示例程序:
#include <stdio.h>
int main()
{
int a = 5; /* Declares a variable, and set the value to 5 */
int *p = &a; /* Declares a pointer, and makes it point to the location of `a` */
/* The actual value of `p` is the address of `a` */
printf("Value of a: %d\n", a); /* Will print 5 */
printf("Value of p: %d\n", p); /* Will print a large number */
printf("The address of a: %d\n", &a); /* Prints the same large number as `p` above */
printf("The contents p: %d\n", *p); /* Prints 5 */
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我希望这个简单的程序可以帮助你更多地理解指针,特别是&和*运算符之间的区别.