繁体   English   中英

在C结构中分配字符

[英]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.

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