【问题标题】:Not fully understanding pointers (C)不完全理解指针(C)
【发布时间】:2021-12-19 02:10:29
【问题描述】:

我必须以“add # # ... #”(# 只是一个数字)的形式输入文本,并将值创建并存储为结构中的顶点。每当我输入“添加”时,我都会遇到分段错误。我相信这是因为我对指针的使用是错误的,但我不确定如何。 这是对 C 课程的介绍,因此我很感激遵循这种简单程度的帮助。

下面是调用我的添加函数(handleAdd)的主文件

int main() {
    printf("Create a polygon using the add command. Valid commands are add, summary, turn, shift, and quit.\n");
    while (1) { //infinite while loop...
        char* cmdLine;
        char* command;
        char* input;
        printf(">>");
        gets(cmdLine);
        command = strtok(cmdLine, " "); //first word
        input = strtok(NULL, ""); //dont understand

        if (strcmp(command, "quit") == 0) //if command == "quit"
             break;
        else if (!strcmp(command, "add")) { //if command == "add"
            if ((input) == NULL) //add\n
                printf("Too few aguments for add command! It must be in the form of add x1 y1 x2 y2 xn yn.\n");
            else
                printf("test1");

            handleAdd(input);
        }

接下来的代码是实际的handleAdd函数

handleAdd(char* addCommand) {
   printf("test1");
   char addCmds[50];
   printf("test2");

   while (addCommand != NULL) {
       printf("test1");
       int i = 0;
       //addCmds[i];
       addCommand = strtok(NULL," ");
   }

   size_t cmdLength = strlen(addCommand);

   for (int i = 1; i <= cmdLength; i++) { //i = 1 becaue 0 has "add"
       if (*(addCommand + i) % 2 == 0) { //if this is even, assign to yCoords
           *(yCoords+(i-1)) = *(addCommand+i); //doubtful it works
       }

       if (*(addCommand + i) % 2 != 0) { //if this is odd, assign to xCoords
           *(xCoords+(i-1)) = *(addCommand+i); //doubtful it works
       }
   } 
}

【问题讨论】:

  • char* cmdLine 。那是一个未初始化的指针。在尝试将其用于写入之前,您需要将其指向有效的内存缓冲区。旁白:Why is the gets function so dangerous that it should not be used?.
  • 永远不要使用gets。它已被弃用多年,实际上已从 C11 语言中删除,因为 不可能 安全地使用它。这不仅很难 - 这是不可能的。
  • 您应该打开所有编译器警告。他们经常会为你指出问题。 -Wall 甚至对误导性缩进发出警告。
  • 您的代码很难阅读。您应该像学习材料中的示例一样格式化您的代码。即使是专业人士,也很难处理格式不佳的代码。

标签: c pointers segmentation-fault


【解决方案1】:

您声明了cmdLine,但您没有将其指定为数组或使用malloc 分配一些内存。使它成为一个数组(它是最简单的解决方案),如下所示:char cmdLine[100];。并使用fgets(cmdLine, 99, stdin); 读取输入,我使用 99 为每个字符串的尾随 NUL 留出空间。
另外,不要将commandinput 放入数组中。留下它们,因为strtok 自己分配内存。

【讨论】:

    猜你喜欢
    • 2018-02-16
    • 1970-01-01
    • 2013-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多