2

我试图理解以下代码中的按位运算,但这会导致分段错误

#include <stdio.h>
#include <stdint.h>

 main()
 {
     uint16_t newmss = 1024;
     uint8_t  *opt;
     unsigned int i = 0;

     opt[i] = (newmss & 0xff00) >> 8;
     opt[i+1] = newmss & 0x00ff;

     fprintf(stderr, "opt[0] is %d", opt[0]);
     fprintf(stderr, "opt[1] is %d", opt[1]);

 }

编译gcc -g -o shift shift.c

然后执行移位,我得到分段错误

# ./shift
Segmentation fault

using gdb to debug

(gdb) run
Starting program: /home/vincent/shift

root@vincent-desktop:/home/vincent# gdb shift
GNU gdb (GDB) 7.1-ubuntu

(gdb) run
Starting program: /home/vincent/shift

Program received signal SIGSEGV, Segmentation fault.
0x0804843f in main () at shift.c:11
11      opt[i] = (newmss & 0xff00) >> 8;

任何人都可以阐明我做错了什么导致分段错误吗?

4

1 回答 1

7

问题不在于轮班,而是您没有为opt.

解决此问题的一种方法如下:

 uint8_t  opt[2];
于 2013-06-07T20:11:28.290 回答