c程序如何打印结构变量持有的char数组?

时间:2017-07-18 08:41:40

标签: c arrays struct char

如何打印结构变量include snippets/ssl-example.com.conf; include snippets/ssl-params.conf; server { listen 80 default_server; listen [::]:80 default_server; listen 443 ssl default_server; listen [::]:443 ssl default_server; return 301 https://www.example.com$request_uri; } server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name www.example.com; ... } 中保存的char数组?

我试过了:

char binary_filename

但是,我收到错误printf("Binary file name is : %s \n", prv_instance_t.binary_filename);

这是结构定义。

error: expected expression before ‘prv_instance_t’

2 个答案:

答案 0 :(得分:2)

您正在使用该类型本身。要访问结构的成员,您必须首先声明该结构的实例。例如,this will print Hello World

#include <stdio.h>
#include <string.h>

#define BINARY_FILE_NAME_MAXLEN 10

typedef struct _prv_instance_
{
    char binary_filename [BINARY_FILE_NAME_MAXLEN];
} prv_instance_t;


int main()
{
    prv_instance_t foo, bar;
    strcpy(foo.binary_filename, "Hello");
    strcpy(bar.binary_filename, "World");

    printf("%s %s\n", foo.binary_filename, bar.binary_filename);
    return 0;
}

您尝试做的与

类似
printf("%d", int);

答案 1 :(得分:0)

只需删除typedef关键字即可。

当前定义未定义变量,但会生成两个等效类型prv_instance_tstruct _prv_instance_。根据您的问题,我了解prv_instance_t应该是_prv_instance_类型的实例(变量),关键字typedef是不必要的。

您的printf可以使用:

#define BINARY_FILE_NAME_MAXLEN   10

struct _prv_instance_
{
    /*
    * The first two are mandatories and represent the pointer to the next instance and the ID of this one. The rest
    * is the instance scope user data (uint8_t power in this case)
    */
    struct _prv_instance_ * next;   // matches lwm2m_list_t::next
    uint16_t shortID;               // matches lwm2m_list_t::id
    uint8_t  power;
    uint8_t  reset;
    double   dec;
    char binary_filename[BINARY_FILE_NAME_MAXLEN];
} prv_instance_t;

以及以下一个:

#define BINARY_FILE_NAME_MAXLEN   10

struct _prv_instance_
{
    /*
    * The first two are mandatories and represent the pointer to the next instance and the ID of this one. The rest
    * is the instance scope user data (uint8_t power in this case)
    */
    struct _prv_instance_ * next;   // matches lwm2m_list_t::next
    uint16_t shortID;               // matches lwm2m_list_t::id
    uint8_t  power;
    uint8_t  reset;
    double   dec;
    char binary_filename[BINARY_FILE_NAME_MAXLEN];
};

struct _prv_instance_ prv_instance_t;