[英]Copy string to element of struct array
I'm attempting to copy a C-string, which is read in from a file to an element of a struct array, but it is not copying. 我正在尝试复制一个C字符串,该字符串是从文件中读取到struct数组的元素中的,但是它不是在复制。 When I attempt to print, the word is not there. 当我尝试打印时,单词不存在。 I'm kind of new to C. Below is my code. 我是C语言的新手。以下是我的代码。 Many thanks for your help. 非常感谢您的帮助。
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;
}
array[count]
doesn't allocate the memory. array[count]
不分配内存。 I believe what you're trying to implement here is single-linked list of strings . 我相信您要在此处实现的是字符串的单链接列表 。
What you're trying to do can be achieved, but you'd need to allocate memory for array
by using malloc/free combo. 您尝试做的事情可以实现,但是您需要使用malloc / free组合为array
分配内存。 What's more, what you're trying to achieve should by done by either making Node.word
an array of fixed size OR a pointer and allocating the memory on Node-by-Node basis. 此外,您要实现的目标应通过使Node.word
成为固定大小的数组或指针,然后逐个节点分配内存来完成。
Length of an array cannot be retrieved by use of sizeof
operator as sizeof
is evaluated in compile and it'll always return a size of a pointer on your platform. 数组的长度不能通过使用sizeof
运算符来获取,因为sizeof
是在编译时求值的,它将始终在平台上返回指针的大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.