gpt4 book ai didi

c - strcpy() 只存储最后一个字符串

转载 作者:行者123 更新时间:2023-11-30 14:46:39 25 4
gpt4 key购买 nike

我想存储包含字符串的数组元素,以便通过共享内存段访问它。我目前正在使用 strcpy(),但它显​​然只存储数组中的最后一个字符串。我如何让它存储数组中的所有 4 个字符串?目前我只能选择要发送的行(例如带有以下两个循环的第一行:

这是我在服务器程序中的循环:

for(int j = 0; j < 1;j++){
strcpy(mem,words);
}

和客户端程序:

for(int i = 0; i < 1; i++){
printf("%s\n",mem);
}

这是完整的服务器程序:

int main() {
const key_t key = 12345678;
FILE *ptr_fp;
char words[600][600];
char *mem;
int i = 0;
ptr_fp = fopen("words.txt","r");

int shmid = shmget(key, sizeof(float)*8, 0644 | IPC_CREAT);

if (shmid < 0) {
perror("shmget");
exit(1);
}

if (ptr_fp != NULL){
while(fgets(words[i],600,ptr_fp )&& i <600){
i++;
}
}

mem = (char *)shmat(shmid,NULL,0);

if(mem == (char *)-1){
perror("shmat error\n");
exit(1);
} else {
for(int j = 0; j < 1;j++){
strcpy(mem,words);
}
printf("Memory is attached\n");
}

return 0;
}

最佳答案

这看起来像是一个复制粘贴错误。

在此 while 循环中,i 得到更新。

 while(fgets(words[i],600,ptr_fp )&& i <600) {
i++;
}

for 循环中,j 应与控制表达式中的 i 进行比较,而不是与 1< 进行比较

 for(int j = 0; j < 1; j++) {
strcpy(mem,words);
}

我认为上面应该改为:

 for(int j = 0, k = 0; j < i; j++) {
strcpy((mem + k),words[j]);
k = k+ strlen(words[j]);
}

关于c - strcpy() 只存储最后一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52074382/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com