我宣布了一个数组:
char * words[1000] = {NULL};
现在我有一系列分叉子进程向该数组添加单词,但它们不会影响父程序。我怎么能改变它?
答案 0 :(得分: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);
}
}
答案 1 :(得分:0)
试试这个你得到的支架错误:
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);
}
}
答案 2 :(得分: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
*/
答案 3 :(得分:0)
嗯,对于你的编辑案例:不要使用fork,使用线程,因为那样一切都在一个地址空间中运行...
当然,然后使用互斥锁保护你的单词阵列......
答案 4 :(得分:0)
当您使用fork创建子进程时,每个子进程都会获得自己的数组副本,而当子进程更改数组中的某些内容时,它实际上正在更改自己的副本,对于您要执行的操作,您需要进程间通信(IPC)创建共享内存或创建管道,以便更改所有子代和父代的数组值