代码的分段错误

时间:2012-06-26 04:14:08

标签: c++

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

using namespace std;

union type{
            int a;
            char b;
            int *p;
            char *s;
            int arr[10];
};

int fn(union type *exp){

    exp->p = exp->p+1;
    cout << *(exp->p);
    cout << "\n";
return 0;
}

int main(){

    union type *str;
    str->a = 10;
    str->b = 'n';
    str->p = &(str->a);
    cout << (str->p);
    cout << "\n";
    fn(str);
    cout << str->p;
    cout << "\n";
return 0;
}

这段代码给了我分段错误。是因为我需要使用malloc显式地为联合分配内存吗?我是编码和尝试学习c ++的新手。

2 个答案:

答案 0 :(得分:3)

  

这段代码给了我分段错误。是因为我需要   使用malloc ??

显式地为联合分配内存

右。您的str指针未指向有效的内存位置,甚至未初始化。因此,在撰写str->a之前,您需要将str设置为某些内容。

答案 1 :(得分:1)

您正在声明指向联合的指针,但指针未指向任何有效的内存,您需要malloc / new。它指向的是未定义的(垃圾指针)。

相关问题