简体   繁体   English

无法将int分配给C中已解引用的int

[英]Cannot assign int to dereferenced int in C

I am lost. 我搞不清楚了。 I cannot assign an int to a dereferenced int * . 我无法将int分配给已取消引用的int *

  printf("in octave\n");

  int *default_octave;
  printf("attr[%d]: %s\n",i+1,attr[i+1]);

  const char *octave_char = attr[i+1];
  printf("octave_char: %s\n", octave_char);

  int octave_number = atoi(octave_char);
  printf("octave_number: %d\n", octave_number);
  fflush(stdout);

  *default_octave=octave_number;
  printf("in octave pt 2\n");
  fflush(stdout);

This is the output: 这是输出:

in octave
attr[1]: 4
octave_char: 4
octave_number: 4
Segmentation fault

Why? 为什么?

Running the GDB debugger gets to that line and then seg faults, too. 运行GDB调试器到该行,然后进行段错误。

4 4

0            int octave_number = atoi(octave_char);
(gdb) s
41            printf("octave_number: %d\n", octave_number);
(gdb)
octave_number: 4
42            fflush(stdout);
(gdb)
43            *default_octave=octave_number;
(gdb) print octave_number
$1 = 4
(gdb) s

Program received signal SIGSEGV, Segmentation fault.
0x0000000000400a7b in parse_song (song_data=0x7fffffffe7a8, attr=0x602600) at nullaby.c:43
43            *default_octave=octave_number;
(gdb)

I have no idea what I can do to fix this. 我不知道该如何解决。

之所以会出现段错误,是因为您从未初始化default_octave指向可以存储int任何内容。

You have an int pointer . 您有一个int pointer Right. 对。

It just mean you have a variable pointing to some memory area. 这只是意味着您有一个指向某个内存区域的变量。
But you haven't allocated/reserved that memory area. 但是您尚未分配/保留该内存区域。 So it can point to anything. 因此它可以指向任何东西。

And it will surely point to a memory area you don't own, hence the segmentation fault. 而且它肯定会指向您不拥有的存储区,因此出现了分段错误。

You need to allocate memory for the pointer... 您需要为指针分配内存...

For instance: 例如:

 int * default_octave = malloc( sizeof( int ) );

Or you may also use: 或者您也可以使用:

int   default_octave_val;
int * default_octave = &default_octave_val;

Either you allocate memory to store your int (and then get a pointer to a valid memory area), or you create a pointer to an existing memory area (in the given example, a stack address). 您可以分配内存来存储int(然后获得一个指向有效内存区域的指针),或者创建一个指向现有内存区域的指针(在给定的示例中为堆栈地址)。

Then you can de-reference that pointer, as it points to a valid memory area. 然后,您可以取消引用该指针,因为它指向有效的内存区域。
If it don't, you'll have a segmentation fault, or a bus error, depending on your OS. 如果不是,则将出现分段错误或总线错误,具体取决于您的操作系统。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM