gpt4 book ai didi

c - 使用指针从方法获取 char 数组值。

转载 作者:行者123 更新时间:2023-11-30 19:28:56 24 4
gpt4 key购买 nike

我一直在努力实现以下目标:我的目标是使用 main() 中的指针来访问 method() 中创建的元素。

// takes in address of pointer
int method(char** input) {
char *buffer = malloc(sizeof(char)*10);

buffer[0] = 0x12;
buffer[1] = 0x34;
buffer[2] = 0xab;

*input = & buffer;

printf("%x\n", *buffer); // this prints 0x12
printf("%x\n", &buffer); // this prints address of buffer example: 0x7fffbd98bf78
printf("%x\n", *input); // this prints address of buffer

return 0;
}

int main(){

char *ptr;
method(&ptr);

printf(%p\n", ptr); // this prints address of buffer

//this does not seem to print out buffer[0]
printf(%x\n", *ptr);

}

我想打印缓冲区值的每个元素,如使用 ptr 由 method() 创建的。关于我如何做到这一点有什么建议吗?

我不确定我是否误解了什么,但我认为 ptr 指向缓冲区的地址。因此,取消引用会给我 buffer[0]?

谢谢。

最佳答案

这是代码的已修复和注释版本。评论里问一下有没有。你不明白。

#include <stdio.h>
#include <stdlib.h>

// takes in address of pointer

//Hex: 0xab is larger than the max value of a signed char.
//Most comilers default to signed char if you don't specify unsigned.
//So you need to use unsigned for the values you chose

int method(unsigned char** input) { //<<< changed
unsigned char *buffer = malloc(sizeof(char)*10);

//Check for malloc success <<< added
if(!buffer)
exit(EXIT_FAILURE);

buffer[0] = 0x12;
buffer[1] = 0x34;
buffer[2] = 0xab;
//I recommend not to mix array notation and pointer notation on the same object.
//Alternatively, you could write:

*buffer = 0x12;
*(buffer + 1) = 0x34;
*(buffer + 2) = 0xab;

//buffer already contains the address of your "array".
//You don't want the address of that address
*input = buffer; //<<< changed (removed &)

printf("%x\n", *buffer); // this prints 0x12
//Not casting &buffer will likely work (with compiler warnings
//But it is better to conform. Either use (char *) or (void *)
//<<< added the cast for printf()
printf("%p\n", (char *)&buffer); // this prints address of buffer example: 0x7fffbd98bf78
printf("%p\n", *input); // this prints address of buffer

return 0;
}

int main(){
unsigned char *ptr;
method(&ptr);

printf("%p\n", ptr); // this prints address of buffer

//this does not seem to print out buffer[0]
for(int i = 0; i < 3; i++){
//<<< changed to obtain content of buffer via ptr for loop.
unsigned char buf_elem = *(ptr + i);
printf("buffer[%d] in hex: %x\t in decimal: %d\n", i, buf_elem, buf_elem);
}

// Don't forget to free the memory. //<<< changed
free(ptr);
}

关于c - 使用指针从方法获取 char 数组值。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53457637/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com