简体   繁体   English

结构问题

[英]C struct problem

I am a C beginner, and I am curious why this gives me a Seg Fault everytime: 我是C初学者,我很好奇为什么每次都会给我一个Seg Fault:

#include <stdio.h>
#include <stdlib.h>

struct Wrapper {
  int value;
};

int main () {
  struct Wrapper *test;
  test->value = 5;

  return 0;
}

I know I don't fully understand pointers yet, but I thought that 我知道我还不完全了解指针,但是我认为

struct_ptr->field 

is the same as 是相同的

(*struct_ptr).field

so trying to make an assignment right to the field should be ok. 因此尝试向该字段分配权限应该没问题。 This works like expected: 这像预期的那样工作:

struct Wrapper test;
test.value = 5;

but I am curious why using the pointer causes a Seg Fault. 但我很好奇为什么使用指针会导致段错误。

I am on Ubuntu 9.04 (i486-linux-gnu), gcc version 4.4.1 我在Ubuntu 9.04(i486-linux-gnu),gcc版本4.4.1上

You didn't assign the pointer to anything. 您没有将指针分配给任何东西。 It's an uninitialized pointer pointing to who knows what, so the results are undefined. 这是一个未初始化的指针,指向谁知道什么,因此结果是不确定的。

You could assign the pointer to a dynamically created instance, like this: 您可以将指针分配给动态创建的实例,如下所示:

int main () {
  struct Wrapper *test;
  test = (struct Wrapper *) malloc(sizeof(struct Wrapper));
  test->value = 5;
  free(test);

  return 0;
}

EDIT: Realized this was C, not C++. 编辑:意识到这是C,而不是C ++。 Fixed code example accordingly. 相应地修复了代码示例。

You need to create an instance of Wrapper first: 您需要首先创建Wrapper的实例:

struct Wrapper *test;
test = new struct Wrapper;
test->Value = 5;

Good luck. 祝好运。

You are using an uninitialised pointer, hence the segfault. 您正在使用未初始化的指针,因此使用了段错误。 Catching this kind of error is possible, if you turn on some more warnings, using -Wall for example 如果打开更多警告,例如-Wall ,则可能会捕获此类错误。

You need to use -Wall in conjonction with some optimisation (-On) for the warning to appear. 您需要结合使用-Wall和一些优化(-On)才能显示警告。 For instance, compiling your code with 例如,使用

gcc -Wall -O2 -c test.c

resulted in the following error message : 导致以下错误消息:

test.c: Dans la fonction «main» :
test.c:10: attention : «test» is used uninitialized in this function

While using french word, this compiler message is not an insult but a warning ;) See below for a code allocating memory for your test pointer 使用法语单词时,此编译器消息不是侮辱,而是警告;)请参见下面的代码,为测试指针分配内存

int main () {
  struct Wrapper *test;
  test = malloc(sizeof(struct Wrapper))
  if(test == NULL) {
  /* error handling */
  }
  test->value = 5;
  free(test)

  return 0;
}

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

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