通过使用指针从方法获取char数组值。

时间:2018-11-24 11:24:33

标签: c pointers

我一直在努力使以下工作: 我的目标是使用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指向缓冲区的地址。因此,取消引用会给我缓冲区[0]?

谢谢。

1 个答案:

答案 0 :(得分: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);
}