我已经通过指针初始化了一个结构,我也尝试使用指针获得值。我正在分割错误。有任何线索吗?
#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);
}
您需要分配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*