如何从结构指针打印 unsigned char 数组?

How to print a unsigned char array from a pointer of a structure?

我正在尝试通过函数参数调用函数。我试图调用的函数将结构作为参数。我可以调用所需的函数,但在尝试打印 unsinged char 数组时,我得到 Segmentation fault (core dumped).

我的代码是,

//char_array.c


#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <inttypes.h>

# define SIZE 20

static struct test{
   unsigned char in[SIZE];
   unsigned char out[SIZE];
}teststruct;

int func2 (struct test *test_func2){
    printf("Inside func2 function\n");
    printf("Inside func2, msg is : %s\n", &test_func2->in);
    return 1;
}

void func1( struct test *test_func1, int (*f)(struct test)){
    printf("Inside func1, msg is:  %s\n", &test_func1->in);

    // calling function
    (*f)(*test_func1);
}

int main(){

    struct test test_main;
    memcpy(teststruct.in,"This is test ", sizeof(teststruct.in));

    test_main=teststruct;

    //check values
    printf("test_main.in is: %s\n", test_main.in);

    // calling func2 from func1
    func1(&test_main,func2);

}

输出:

$./char_array 
 test_main.in is: This is test 
 Inside func1, msg is:  This is test 
 Inside func2 function
 Segmentation fault (core dumped)

我正在像下面这样编译我的代码,

gcc -O0 -g -Wall -Wextra -pedantic -fomit-frame-pointer -o char_array char_array.c

对我做错了什么有什么帮助吗?

func2 的类型是 - int (struct test *) 并且您将 func2 指针作为 2nd 参数传递给 func1()其2nd参数类型为int (*)(struct test)。这是类型不匹配。 func1()函数的2nd参数类型需要修正:

void func1( struct test *test_func1, int (*f)(struct test *))
                                                         ^^^

func2()函数的参数类型为-struct test *。也就是说,它可以接收struct test类型变量的地址。这里,

    // calling function
    (*f)(*test_func1);

指针 f 保存 func2() 函数的地址,您传递的参数的类型为 struct test。又是类型不匹配。相反,它应该是

    // calling function
    (*f)(test_func1);
        ^^^

因为 test_func1struct test * 类型,与 func2() 函数的参数类型相同。

还有一点,在func2()函数中打印它的值时,你不需要给&加上test_func2->in

    printf("Inside func2, msg is : %s\n", test_func2->in);
                                         ^^^

打印 test_func1->infunc1() 函数也是如此。