【问题标题】:Copy string to element of struct array将字符串复制到结构数组的元素
【发布时间】:2017-03-17 16:41:32
【问题描述】:

我正在尝试复制一个 C 字符串,该字符串是从一个文件中读入的到一个结构数组的一个元素中,但它不是在复制。当我尝试打印时,这个词不存在。我对 C 有点陌生。下面是我的代码。非常感谢您的帮助。

typedef struct Tree{
    int numTimes; //number of occurrences
    char* word; //the word buffer
}Node;

#include "proj2.h"
#include <ctype.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[]){

    FILE* readIn; //read file pointer
    FILE* writeOut; //write file pointer
    char buffer[18]; //allocate buffer ***please do not fuzz
    int length = 0;
    int count = 0;
    Node* array = (Node*) malloc(sizeof(Node));

    /*if(argc < 3){ //if the number of command line arguments is < 3, return EXIT_FAILURE
     return EXIT_FAILURE;
     }*/
    argv[1] = "/Users/magnificentbastard/Documents/workspaceCPP/proj2/Password.txt"; //****testing
    argv[2] = "outFile.txt"; //****testing

    readIn = fopen(argv[1], "r"); //opens the selected argument file for reading
    writeOut = fopen(argv[2], "w"); //opens the selected argument file for writing

    if(readIn == NULL){ //if there
        printf("ERROR: fopen fail.\n");

        return EXIT_FAILURE; //exits if the file opens
    }

    while(fscanf(readIn, "%18s", buffer) == 1){ //loop to read in the words to the buffer
        count++; //counts the words coming in
        modWord(buffer); //modifies the words coming in

        array = (Node*)realloc(array, sizeof(Node));

        for(int i = 0; i < count; i++){ //****not copying over...HELP
            strcpy(array[i].word, buffer);
        }
    }

    //Node array[count];
    fprintf(stderr, "%d ", count); //***for testing purposes only
    int elements = sizeof(array)/sizeof(array[0]); //***testing assigns num elements
    fprintf(stderr, "%d ", elements); //***testing prints num elements

    fclose(readIn); //closes the in-file
    fclose(writeOut); //closes the out-file

    return EXIT_SUCCESS;
}

【问题讨论】:

  • 在不确定时使用具有自动存储持续时间的对象的值的未定义行为。
  • @JohnColeman 我的原始代码中有一个指向 word 的指针,它只是没有复制过来。那不是我的问题。
  • @JohnColeman 我试过在我的结构中使用一个字符缓冲区并且也只是在做 strcpy,但它没有复制。

标签: c arrays struct c-strings strcpy


【解决方案1】:

array[count] 不分配内存。我相信您在这里尝试实现的是single-linked list of strings

您尝试做的事情可以实现,但您需要使用 malloc/free 组合为 array 分配内存。更重要的是,您想要实现的目标应该是通过将 Node.word 设为固定大小的数组或指针并逐个节点分配内存。

无法通过使用 sizeof 运算符检索数组的长度,因为 sizeof 在编译中进行评估,并且它始终会返回您平台上指针的大小。

【讨论】:

  • 在这种情况下,你是对的——sizeof() 值是在编译时评估的。如果代码使用 VLA(可变长度数组),则应用到 VLA 的 sizeof() 将在运行时进行评估。
猜你喜欢
  • 1970-01-01
  • 2017-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-21
  • 2018-03-19
  • 2013-07-19
  • 1970-01-01
相关资源
最近更新 更多