C结构初始化和分段错误

时间:2019-05-20 07:04:01

标签: c

我已经通过指针初始化了一个结构,并且我也尝试使用指针来获取值。我遇到了细分错误。有线索吗?

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


int main(void){
    struct MemData{
        char* FileName;
        int LastByteLength;
        int ReadPointer;
        int WritePointer;
        char Data[ 512000];//MEMORY BLOCK SIZE: 500 KB
    };
    struct MemData* M;
    M->FileName=(char*)"xaa";
    M->LastByteLength=0;
    M->ReadPointer=-1;
    M->WritePointer=-1;
    printf("\n%s", M->FileName);
    printf("\n%d", M->LastByteLength);
    printf("\n%d", M->ReadPointer);
    printf("\n%d", M->WritePointer);

}

1 个答案:

答案 0 :(得分:1)

您需要分配M。

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


int main(void){
  struct MemData{
     char* FileName;
     int LastByteLength;
     int ReadPointer;
     int WritePointer;
     char Data[ 512000];//MEMORY BLOCK SIZE: 500 KB
  };
  struct MemData* M;
  M = malloc(sizeof(*M));
  M->FileName="xaa";
  M->LastByteLength=0;
  M->ReadPointer=-1;
  M->WritePointer=-1;
  printf("\n%s", M->FileName);
  printf("\n%d", M->LastByteLength);
  printf("\n%d", M->ReadPointer);
  printf("\n%d", M->WritePointer);
  free(M);
}

尝试上面的代码,它应该可以工作。

正如Broman在评论中建议的那样,我编辑了答案,删除了不必要的“(char *)”,因为字符串文字已经具有char *类型了