[英]Assigning a char in a C struct
本質上,我遇到了一個非常基本的問題……C方面的一些新知識。我正在制作一個存儲名稱(字符串)及其類型(字符,“ D”或“ F”)的節點結構。 字符串工作正常,char似乎沒有。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char line[128];
char command[16], pathname[64];
char dirname[64], basename[64];
typedef struct {
char name[64];
char type;
struct NODE *childPtr, *siblingPtr, *parentPtr;
} NODE;
NODE *root, *cwd;
initialize(){
root = malloc(sizeof(NODE));
strcpy(root->name, "/");
root->type = 'D';
}
main()
{
while(1){
printf("Input a command: ");
gets(line);
printf("Command inputed -> %s\n", line);
printf("Root's name -> %s\n", root->name);
printf("Root's type -> %c\n", root->type);
}
}
現在,當我執行此操作時,它會很好地打印出名稱,但是應該在應該打印類型的行上顯示Segmentation Faults。 我還嘗試使用“ root.type ='D';”來定義類型。 也一樣
編輯:現在復制粘貼的確切代碼。 有些東西沒有用,因為我只是測試它的第一部分,仍在進行中。
聲明結構時出現錯誤...您將結構拼寫錯誤為'strcut'。
你還需要做
root = malloc(sizeof(*root));
...
free(root);//should be the last line
return 0;
編輯:永遠不要使用gets()
,幾乎可以肯定的是,您會遇到問題...
編輯2:應該為函數initialize()
返回類型為void
。 然后,您必須在main中調用該函數。 應該是這樣的。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
char line[128];
char command[16], pathname[64];
char dirname[64], basename[64];
typedef struct {
char name[64];
char type;
struct NODE *childPtr, *siblingPtr, *parentPtr;
} NODE;
NODE *root, *cwd;
void initialize(){
root = malloc(sizeof(*root));
strcpy(root->name, "/");
root->type = 'D';
}
main()
{
initialize();
while(1){
printf("Input a command: ");
fgets(line,128, stdin);
printf("Command inputed -> %s\n", line);
printf("Root's name -> %s\n", root->name);
printf("Root's type -> %c\n", root->type);
if (line[0] == 'q' && strlen(line)==2)break;//added so I can break loop....
}
free(root);
}
如果您缺少一些頭文件,並且拼寫了錯誤的結構,則還應該釋放為該結構分配的內存。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
char name[64];
char type;
} NODE;
NODE *root;
int main()
{
root = malloc(sizeof(NODE));
strcpy(root->name, "test");
root->type = 'D';
printf("Name = %s\n", root->name);
printf("Type = %c\n", root->type);
free(root);
return 0;
}
typedef strcut
應該是結構 - >這應該是一個編譯錯誤
那應該做到的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.