相关疑难解决方法(0)

char s []和char*s有什么区别?

在C中,可以在声明中使用字符串文字,如下所示:

char s[] = "hello";
Run Code Online (Sandbox Code Playgroud)

或者像这样:

char *s = "hello";
Run Code Online (Sandbox Code Playgroud)

那么区别是什么呢?我想知道在编译和运行时的存储持续时间实际发生了什么.

c string constants char

495
推荐指数
6
解决办法
33万
查看次数

结构声明结束时这[1]的目的是什么?

我正在窥探我的MSP430微控制器的头文件,我遇到了这个<setjmp.h>:

/* r3 does not have to be saved */
typedef struct
{
    uint32_t __j_pc; /* return address */
    uint32_t __j_sp; /* r1 stack pointer */
    uint32_t __j_sr; /* r2 status register */
    uint32_t __j_r4;
    uint32_t __j_r5;
    uint32_t __j_r6;
    uint32_t __j_r7;
    uint32_t __j_r8;
    uint32_t __j_r9;
    uint32_t __j_r10;
    uint32_t __j_r11;
} jmp_buf[1]; /* size = 20 bytes */
Run Code Online (Sandbox Code Playgroud)

我知道它声明了一个匿名结构和typedef它jmp_buf,但我无法弄清楚它是什么[1].我知道它声明jmp_buf是一个有一个成员(这个匿名结构)的数组,但我无法想象它用于什么.有任何想法吗?

c struct typedef reverse-engineering declaration

95
推荐指数
1
解决办法
3298
查看次数

为什么这样的结构包含两个只包含一个元素的数组字段?

请注意:这个问题不是(struct中的一个元素数组)的重复

以下代码摘自Linux内核源代码(版本:3.14)

struct files_struct
{
    atomic_t count;
    struct fdtable __rcu *fdt;
    struct fdtable fdtab;

    spinlock_t file_lock ____cacheline_aligned_in_smp;
    int next_fd;
    unsigned long close_on_exec_init[1];
    unsigned long open_fds_init[1];
    struct file __rcu * fd_array[NR_OPEN_DEFAULT];
};
Run Code Online (Sandbox Code Playgroud)

我只是想知道为什么close_on_exec_initopen_fds_init被定义为包含一个元素的数组,而不是仅仅定义为unsigned long close_on_exec_init;unsigned long open_fds_init;.

c linux arrays struct idioms

10
推荐指数
2
解决办法
364
查看次数

C char数组作为指针

我想明白:

  • 为什么会发生这种情况,有时char[1]在C中使用char*(为什么这样做?)和
  • 内部如何工作(发生了什么)

提供以下示例程序:

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

struct test_struct {
    char *a;
    char b[1];
} __attribute__((packed)); ;

int main() {

    char *testp;
    struct test_struct test_s;

    testp = NULL;
    memset(&test_s, 0, sizeof(struct test_struct));

    printf("sizeof(test_struct) is: %lx\n", sizeof(struct test_struct));

    printf("testp at: %p\n", &testp);
    printf("testp is: %p\n", testp);

    printf("test_s.a at: %p\n", &test_s.a);
    printf("test_s.a is: %p\n", test_s.a);

    printf("test_s.b at: %p\n", &test_s.b);
    printf("test_s.b is: %p\n", test_s.b);

    printf("sizeof(test_s.b): %lx \n", sizeof(test_s.b));

    printf("real sizeof(test_s.b): %lx \n", ((void *)(&test_s.b) - (void *)(&test_s.a)) ); …
Run Code Online (Sandbox Code Playgroud)

c arrays pointers

5
推荐指数
1
解决办法
1149
查看次数