在C中,可以在声明中使用字符串文字,如下所示:
char s[] = "hello";
Run Code Online (Sandbox Code Playgroud)
或者像这样:
char *s = "hello";
Run Code Online (Sandbox Code Playgroud)
那么区别是什么呢?我想知道在编译和运行时的存储持续时间实际发生了什么.
我正在窥探我的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是一个有一个成员(这个匿名结构)的数组,但我无法想象它用于什么.有任何想法吗?
请注意:这个问题不是(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_init和open_fds_init被定义为包含一个元素的数组,而不是仅仅定义为unsigned long close_on_exec_init;和unsigned long open_fds_init;.
我想明白:
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)