Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/fortran/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
strcpy()仅存储最后一个字符串_C - Fatal编程技术网

strcpy()仅存储最后一个字符串

strcpy()仅存储最后一个字符串,c,C,我想存储包含字符串的数组元素,以便通过共享内存段进行访问。我目前正在使用strcpy,但它显然只存储数组中的最后一个字符串。如何使它存储数组中的所有4个字符串?目前,我只能选择要发送的线路,例如,具有以下两个循环的第一条线路: 以下是我在服务器程序中的循环: for(int j = 0; j < 1;j++){ strcpy(mem,words); } int main() { const key_t key = 12345678; FILE *p

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

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

for(int j = 0; j < 1;j++){
            strcpy(mem,words);
}
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;
}
和客户端程序:

for(int i = 0; i < 1; i++){
    printf("%s\n",mem);
}
以下是完整的服务器程序:

for(int j = 0; j < 1;j++){
            strcpy(mem,words);
}
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循环中,我得到了更新

 while(fgets(words[i],600,ptr_fp )&& i <600) {
     i++;
 }
我认为上述内容应改为:

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

仅供参考,fgets循环中多部分布尔求值的顺序是向后的。i检查应该是第一个。为什么共享内存的大小是sizeoffloat*8,而不是在其中存储浮点数?。。。您在问题中提到的这4个字符串在哪里?对不起,字符串是以文字形式存储的。当我将for循环更改为您的建议时,它会从每行中获取第一个字符,然后继续打印最后一行的剩余字符尝试以下操作并让我知道:forint j=0,k=0;j