简体   繁体   English

如何从char数组强制转换/ copy以便将其存储在char指针数组中?

[英]How do I cast /copy from a char array so that I may store it in a char pointer array?

I'm working on a project that involves reading and /or writing from a text file. 我正在从事一个涉及从文本文件读取和/或写入的项目。 Currently the only data I'm attempting to extract from the text file are names. 目前,我尝试从文本文件中提取的唯一数据是名称。 My goal is to be able to store specific names in a character pointer array such that Char[n] will have a name assigned to it for any given n in the array. 我的目标是能够在字符指针数组中存储特定的名称,这样Char[n]将为数组中的任何给定n分配一个名称。

The problem I seem to be having is that I'm setting my character pointer element to another character array where I'm storing the read value from the text file. 我似乎遇到的问题是我将字符指针元素设置为另一个字符数组,并在其中存储了来自文本文件的读取值。

For example, if I read a name from the text file and set Name[] equal to that name then later set Char[0] = Name then Char[0] will always change when Name does. 例如,如果我从文本文件中读取一个名称,并设置Name[]等于名字后来设置Char[0] = Name ,然后Char[0]总是会改变的时候Name一样。

I've attempted to write the string directly to Char[0] , for example, but then my program crashes just after I attempt to read and store the value. 例如,我曾尝试将字符串直接写入Char[0] ,但是在尝试读取和存储值之后,我的程序崩溃了。 Therefore, I've resorted to this convoluted route of assigning a separate character array to the name I scan and setting one of my elements to it. 因此,我采用了这种复杂的方法,即为我扫描的名称分配一个单独的字符数组,并为其设置一个元素。

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main()
{
    FILE * inf = fopen("UserNames.txt", "r");
    char User[125];
    int err, TopNameNumber = 10;
    char *UserNames[TopNameNumber];

    if (inf == NULL) 
    { 
        printf("ERROR: No name file detected."); 
        return 0; 
    }

    for(int i = 0; i < TopNameNumber i++)
    {
        //This reads from my .txt file
        err = fscanf(inf, " %s", User);

        if(err == EOF)
            break;

        //This shows me what user was read from the text file
        printf("User read %d: %s\n", i+1, User); 

        //Program assigns the pointer address of User to Names[i]
        //This is where I'm having trouble
        UserNames[i] = User;
    }

    for(int c = 0; c < 3; c++)
    {
        // This always just prints out the last name read from the .txt file 
           for every name
        printf("Name #%d: %s\n", c, UserNames[c]);
    }

    return 0;
}

I've been at this for a few days and I've found some interesting avenues which could possibly solve my problem, such as copying the string with strcpy() function, or perhaps casting User to something. 我已经呆了几天了,我发现了一些有趣的途径可以解决我的问题,例如使用strcpy()函数复制字符串,或者将User强制转换为某种东西。 All to no avail so far, however. 到目前为止,一切都无济于事。

I would appreciate any advice as to what you think is the best solution to pursue if the solution isn't obvious here. 如果您认为最佳解决方案在这里并不明显,那么我将不胜感激。 I would like to avoid doing everything character by character, but I suppose I would be willing to in the long run. 我想避免一个字一个字地做所有事情,但从长远来看,我想我愿意。

I apologize for perhaps an unclear question, this is my first time asking one, and I'm just trying to give as much context as possible :) 我为一个不清楚的问题表示歉意,这是我第一次问一个问题,我只是在尝试提供尽可能多的背景信息:)

My code compiles with no warnings or errors as of right now. 到目前为止,我的代码编译时没有警告或错误。

the blatant error I see is here: 我看到的公然错误是在这里:

    //Program assigns the pointer address of User to Names[i]
    //This is where I'm having trouble
    UserNames[i] = User;

reusing the same buffer for all usernames isn't going to fly. 所有用户名重复使用相同的缓冲区不会成功。 On the other hand, you cannot use strcpy because no memory is allocated. 另一方面,由于未分配内存,因此无法使用strcpy You can use strdup which allocates & copies the string. 您可以使用strdup分配和复制字符串。

UserNames[i] = strdup(User);

or for the purists (since strdup isn't strictly in the standard): 或对于纯粹主义者(由于strdup严格不在标准中):

UserNames[i] = malloc(strlen(User)+1);
strcpy(UserNames[i],User);

As a security side-note, since the buffer is 125 bytes long, I suggest limiting the input it can accept to 124+nul-termination: 作为安全说明,由于缓冲区的长度为125个字节,因此我建议将其可以接受的输入限制为124 + nul-termination:

err = fscanf(inf, " %124s", User);

Of course, you need to deallocate the strings when no longer used, or you'll get memory leaks if your program doesn't quit or is part of a bigger code. 当然,当不再使用这些字符串时,您需要对其进行分配,否则,如果您的程序不退出或者是更大代码的一部分,则会导致内存泄漏。

free(UserNames[i]); // in a loop in the end, when no longer needed

You need to allocate memory for a separate char[] for each name you read from the file. 您需要为从文件中读取的每个名称分配一个单独的char[]内存。

For example: 例如:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main() {
    FILE *inf = fopen("UserNames.txt", "r");
    if (inf == NULL) {
        printf("ERROR: No name file detected.");
        return 0;
    }

    int err, c = 0;

    const int TopNameNumber = 10;
    char UserNames[TopNameNumber][125];

    for(int i = 0; i < TopNameNumber; i++) {
        err = fscanf(inf, " %124s", UserNames[c]);
        if (err == EOF)
            break;

        printf("User read %d: %s\n", c+1, UserNames[c]);
        ++c;
    }

    fclose(inf);

    for(int i = 0; i < c; i++) {
        printf("Name #%d: %s\n", i, UserNames[i]);
    }

    return 0;
}

Alternatively: 或者:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main() {
    FILE *inf = fopen("UserNames.txt", "r");
    if (inf == NULL) {
        printf("ERROR: No name file detected.");
        return 0;
    }

    char User[125];
    int err, c = 0;

    const int TopNameNumber = 10;
    char* UserNames[TopNameNumber];

    for(int i = 0; i < TopNameNumber; i++) {
        err = fscanf(inf, " %124s", User);
        if (err == EOF)
            break;

        printf("User read %d: %s\n", c+1, User);

        UserNames[c] = malloc(strlen(User) + 1);
        if (UserNames[c] == NULL) {
            printf("ERROR: Memory allocation failed.");
            break;
        }

        strcpy(UserNames[c], User);
        ++c;
    }

    fclose(inf);

    for(int i = 0; i < c; i++) {
        printf("Name #%d: %s\n", i, UserNames[i]);
    }

    for(int i = 0; i < c; i++) {
        free(UserNames[i]);
    }

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM