2016-11-03 4 views
0

파일에서 구조체 배열의 요소로 읽은 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; 
} 
+0

불확실한 동안 자동 저장 기간이있는 객체의 값을 사용하는 경우 정의되지 않은 동작입니다. – EOF

+0

@ JohnColeman 원래 코드에서 단어에 대한 포인터가 있었지만 복사하지 않았습니다. 그건 내 문제가 아니야. –

+0

@ JohnColeman 내 구조체에 문자 버퍼를 가지고 있지만 strcpy를 시도했지만 복사하지 않았습니다. –

답변

1

array[count] 메모리를 할당하지 않습니다. 여기에 구현하려는 것은 single-linked list of strings입니다.

할 수 있습니다.을 달성 할 수 있지만, malloc/free 콤보를 사용하여 array에 메모리를 할당해야합니다. 더 나아가, 달성하고자하는 것은 Node.word을 고정 된 크기의 배열 또는 포인터로 만들고 노드별로 노드를 할당하여 수행해야합니다.

sizeof 연산자를 사용하여 배열의 길이를 검색 할 수 없습니다. sizeof은 컴파일시 평가되며 항상 플랫폼에서 포인터 크기를 반환합니다.

+0

이 문맥에서, 당신은 옳다.'sizeof()'값은 컴파일 할 때 평가된다. 코드가 VLA (가변 길이 배열)를 사용했다면, VLA에 적용된'sizeof()'가 런타임에 평가됩니다. –