【问题标题】:Global Array doesn't update while inside while loop?全局数组在while循环内不更新?
【发布时间】:2013-04-03 16:32:31
【问题描述】:

我有一个结构数组,在 while 循环中我向该数组添加了一些东西,但是当我打印出数组时,我得到了错误的输出? (最后添加的元素打印n次,n是我添加的东西的数量)

我用谷歌搜索过这个,我认为这是因为 Bash 中的 while 循环创建了一个子 shell,不太确定。

任何帮助将不胜感激 (请耐心等待,我只是学生!!)

使用 Mac OSX 山狮 Xcode 4 gcc

代码:

#include <stdio.h>
#include <limits.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>

typedef struct{
    char* one;  
    char* two;
} Node;

Node nodes[100];
int count = 0;

void add(char *one,char*two){
    Node newNode = {one,two};
    nodes[count]= newNode;

    printf("one: %s\n",one); 
    printf("two: %s\n",two); 

    count++;
}

void print(){
    int x;
    for (x = 0; x < 10; x++)
        printf("%d : (%s, %s) \n",x,nodes[x].one, nodes[x].two);
}

void check(char **arg)
{
    if(strcmp(*arg, "Add") == 0)
        add(arg[1],arg[2]);
    else if(strcmp(*arg,"print") == 0)
        print();
    else
        printf("Error syntax Enter either: \n Add [item1][item2]\n OR \n print\n");
}

void readandParseInput(char *line,char **arg)
{ 
    if (fgets (line, 512, stdin)!= NULL) {  
        char * pch;
        pch = strtok (line," \n\t");
        int count = 0;
        arg[0] = pch;

        while (pch != NULL)
        {
            count++; 
            pch = strtok (NULL, " \n\t"); 
            arg[count] = pch;
        }
    }else{
        printf("\n");
        exit(0);
    }
}

int main() 
{
    int i;
    for(i = 0;i <100; i++){
        nodes[i].one = ".";
        nodes[i].two = ".";
    }

    char  line[512];             /* the input line                 */
    char  *arg[50];              /* the command line argument      */

    while (1) 
    { 
        readandParseInput(line,arg);
        if(arg[0] != NULL)
            check(arg);
    }
    return(0);
}

【问题讨论】:

  • 如果你正确缩进你的代码,它会帮助你很大。
  • 这与 bash 和 subshel​​l 中的 while 循环无关。你的nodesNode 类型的数组,而不是Node *,所以你不能做Node newNode = {one,two}; nodes[count]= newNode;
  • 如何将这些项目添加到结构中,然后添加到数组 Vicky 中?

标签: c arrays loops while-loop


【解决方案1】:

strtok() 返回指向最初传递的缓冲区中不同元素的指针。这意味着数组中的所有条目都将指向同一个缓冲区的不同元素,命名为line。你需要复制strtok()返回的指针:

无论哪种情况,当不再需要时,内存必须是free()d。

【讨论】:

  • 需要释放什么?缓冲线?
【解决方案2】:

这是因为您对所有输入使用相同的缓冲区。

您需要复制放入结构中的字符串。要么对字符串使用数组并将strcpy 放入其中,要么使用strdup 为字符串分配新内存并在一个函数中进行复制。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 2016-04-24
    • 1970-01-01
    • 1970-01-01
    • 2016-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多