在while循环中,Global Array不会更新?

时间:2013-04-11 13:01:15

标签: c arrays loops while-loop

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

我用google搜索了这个,我认为这是因为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);
}

2 个答案:

答案 0 :(得分:2)

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

在任何一种情况下,当不再需要时,内存必须为free() d。

答案 1 :(得分:0)

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

您需要复制放入结构中的字符串。通过使用字符串数组和strcpy,或者使用strdup为字符串分配新内存并在一个函数中进行复制。