1

我声明了一个数组:

char * words[1000] = {NULL};

现在我有一系列分叉的子进程将单词添加到该数组中,但它们不会影响父程序。我该如何改变呢?

4

5 回答 5

0

您还没有在 while 块内添加 if 块!!!

   while(i < 1000 && words[i] != NULL)
   {
   i++;
 if(i<1000){
    words[i] = (char*) malloc(strlen(temp)+1);
    strcpy(words[i], temp);
   words[i][strlen(words[i])] = '\0';
    printf("Added: %s at location %d\n", words[i], i);
   }
  }
于 2012-12-06T02:56:13.923 回答
0

试试这个,你弄错了 while 大括号:

int i = 0;
while(i < 1000 && words[i] != NULL){
    i++;
    if(i<1000){
        words[i] = (char*) malloc(strlen(temp)+1);
        strcpy(words[i], temp);
        words[i][strlen(words[i])] = '\0';
        printf("Added: %s at location %d\n", words[i], i);
    }
}
于 2012-12-06T02:58:29.307 回答
0

请粘贴整个代码......我编写代码来做我认为你正在做的事情,它对我有用......

    #include <stdio.h>

int main(int argc, char *argv[])
{
  char* words[1000];
  int j;
  for(j = 0; j<1000; j++)
    words[j] = NULL;
  char *temp = "dummy";

  for (j = 0; j < 10; j++)
    {
      int i = 0;
      while(i < 1000 && words[i] != NULL)
        i++;
      printf("Adding something to %d vs %d\n",i,j);
      if(i<1000){
        words[i] = (char*) malloc(strlen(temp)+1);
        strcpy(words[i], temp);
        words[i][strlen(words[i])] = '\0';
        printf("Added: %s at location %d\n", words[i], i);
      }
    }
}

/* prints:
Adding something to 0 vs 0
Added: dummy at location 0
Adding something to 1 vs 1
Added: dummy at location 1
Adding something to 2 vs 2
Added: dummy at location 2
Adding something to 3 vs 3
Added: dummy at location 3
Adding something to 4 vs 4
Added: dummy at location 4
Adding something to 5 vs 5
Added: dummy at location 5
Adding something to 6 vs 6
Added: dummy at location 6
Adding something to 7 vs 7
Added: dummy at location 7
Adding something to 8 vs 8
Added: dummy at location 8
Adding something to 9 vs 9
Added: dummy at location 9
*/
于 2012-12-06T03:04:27.103 回答
0

嗯,对于您的编辑情况:不要使用 fork,使用线程,因为那样一切都在一个地址空间中运行......
当然,然后使用互斥锁来保护您的单词数组......

于 2012-12-06T03:17:07.957 回答
0

当您使用 fork 创建子节点时,每个子节点都会在子节点更改数组中的某些内容时获得自己的数组副本,它实际上是在更改自己的副本,对于您要执行的操作,您需要进程间通信 (IPC),您需要创建一个共享内存或创建管道,以便所有子项和父项的数组值更改

于 2020-05-21T08:50:05.787 回答