尝试创建一个整数和字符串的动态数组?我不确定我在做什么错误的。

huangapple go评论61阅读模式
英文:

Trying to make a dynamic array of int and strings? I am not sure what I am doing wrong

问题

我有一个课堂作业,需要读取一个txt文件并**显示**,**添加**和**删除**键(整数)和值(字符串)。

我想为每个键值对使用一个动态数组(我的教授说如果我这样做可以获得额外的学分)。目前,这是我的代码,我读取了txt文件并将其添加到数组中。

1. 我不确定是否需要创建一个足够存储任何单词的字符串,然后将其复制到更小的char中以减少内存使用(`strcpy(savStr, userStr);`)
2. 我不确定我是否正确地使用动态数组,或者如何添加更多索引
3. 我不确定我是否正确地向数组添加内存

int main(int argc, char **argc) {
// ... (你的代码保持不变)
}


这是txt文件

1,one
2,two
3,three
4,four
5,five
6,six
7,seven

这是添加到数组中的内容

1 - ottffsseven
2 - ttffsseven
3 - tffsseven
4 - ffsseven
5 - fsseven
6 - sseven
7 - seven


<details>
<summary>英文:</summary>

I have a class assignment where I need to take a txt file and **display**, **add**, and **remove** keys (int) and values (strings).

I would like to use a dynamic array for each (my professor said I can get extra credit if I do). Currently, this is what I have, I read the txt file and I add them to the array.

 1. I don&#39;t know if creating a string with enough memory for any word and then copying it to a smaller char for less memory is needed (`strcpy(savStr, userStr);`)
 2. I am not sure if I am doing the dynamic array correctly or how to add more indexes
 3. I dont know if I am adding the memory to the array correctly

int main(int argc, char **argc) {
int userNumber; //to take in user key and key in file
char userStr[1000]; //initial string to take value from user and string
int strL = 1; //find string length of value to find correct memory need to allocate
char savStr[strL]; //value with memory allocate for the size of the string
FILE *fp;
fp = fopen("values.txt", "r");
int *keyArry;
keyArry = (int *)calloc(8, sizeof(int));
char *valueArry;
valueArry = (char *)calloc(8, sizeof(char));
int curr = 0;

while (fscanf(fp, &quot;%d,%s&quot;, &amp;userNumber, userStr) != EOF) {
    strL = strlen(userStr);
    savStr[strL];
    strcpy(savStr, userStr);
    printf(&quot;%d - %s \n&quot;, cuserNumber, savStr);
    keyArry[curr] = userNumber;
    strcpy(&amp;valueArry[curr], &amp;savStr);
    curr++;
}
fclose(fp);
for (int i = 0; i &lt; 7; i++) {
    printf(&quot;%d - %s \n&quot;, keyArry[i], &amp;valueArry[i]);
}
this is the txt file

1,one
2,two
3,three
4,four
5,five
6,six
7,seven

this is the what is added to the array

1 - ottffsseven
2 - ttffsseven
3 - tffsseven
4 - ffsseven
5 - fsseven
6 - sseven
7 - seven



</details>


# 答案1
**得分**: 1

这段代码存在未定义行为,因为`char savStr[strL];`定义了一个`char`数组,长度为1,只足够存储空字符串。将任何较大的内容复制到它会导致未定义的行为。应该使用`char savStr[1000];`代替。在阅读完代码的其余部分后,似乎根本不需要这个额外的数组。

另外要注意的是,`char *valueArry;`定义了一个`char`指针,你将其初始化为指向一个包含8个`char`的数组。你应该改为定义一个指向`char *`数组的指针,并进行正确的初始化。

你的教授希望你使用动态数组,因此如果要存储的元素数量超过了分配的长度,可能需要重新分配它们。

以下是修改后的版本:

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

int main(int argc, char **argv) {
    int userNumber;     // 用于接收用户输入的键和文件中的键
    char userStr[1000]; // 用于接收用户输入的值和字符串
    FILE *fp = fopen("values.txt", "r");
    if (fp == NULL) {
        fprintf(stderr, "无法打开文件 values.txt: %s\n", strerror(errno));
        return 1;
    }
    int size = 8;
    int curr = 0;
    int *keyArry = calloc(size, sizeof(*keyArry));
    char **valueArry = calloc(size, sizeof(*valueArry));
    if (keyArry == NULL || valueArry == NULL) {
        fprintf(stderr, "无法分配数组\n");
        return 1;
    }

    while (fscanf(fp, "%d,%999s", &userNumber, userStr) == 2) {
        if (curr >= size) {
            // 必须重新分配数组
            size += size;
            keyArry = realloc(keyArry, size * sizeof(*keyArry));
            valueArry = realloc(valueArry, size * sizeof(*valueArry));
            if (keyArry == NULL || valueArry == NULL) {
                fprintf(stderr, "无法重新分配数组\n");
                return 1;
            }
        }
        printf("%d - %s\n", userNumber, userStr);
        keyArry[curr] = userNumber;
        valueArry[curr] = strdup(userStr);
        curr++;
    }
    fclose(fp);
    for (int i = 0; i < curr; i++) {
        printf("%d - %s \n", keyArry[i], valueArry[i]);
    }
    return 0;
}
英文:

The code has undefined behavior because char savStr[strL]; defines an array of char with a length of 1, just enough for the empty string. Copying anything larger to it causes undefined behavior. Use char savStr[1000]; instead. After reading the rest of the code it seems this extra array is not needed at all.

Also note that char *valueArry; defines a pointer to char, which you initialize to point to an array of 8 char. You should instead define a pointer to an array of char * and initialize it properly.

You professor wants you to use dynamic arrays, so you may need to reallocate them if the number of elements to store exceeds the allocated length.

Here is a modified version:

#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;string.h&gt;

int main(int argc, char **argc) {
    int userNumber;     //to take in user key and key in file
    char userStr[1000]; //initial string to take value from user and string
    FILE *fp = fopen(&quot;values.txt&quot;, &quot;r&quot;);
    if (fp == NULL) {
        fprintf(stderr, &quot;cannot open file values.txt: %s\n&quot;, strerror(errno));
        return 1;
    }
    int size = 8;
    int curr = 0;
    int *keyArry = calloc(size, sizeof(*keyArray));
    char **valueArry = calloc(size, sizeof(*valueArry));
    if (keyArry == NULL || valueArry == NULL) {
        fprintf(stderr, &quot;cannot allocate arrays\n&quot;);
        return 1;
    }

    while (fscanf(fp, &quot;%d,%999s&quot;, &amp;userNumber, userStr) == 2) {
        if (curr &gt;= size) {
            // must reallocate the arrays
            size += size;
            keyArry = realloc(keyArry, size * sizeof(*keyArry);
            valueArry = realloc(valueArry, size * sizeof(*valueArry);
            if (keyArry == NULL || valueArry == NULL) {
                fprintf(stderr, &quot;cannot reallocate arrays\n&quot;);
                return 1;
            }
        }
        printf(&quot;%d - %s\n&quot;, cuserNumber, userStr);
        keyArry[curr] = userNumber;
        valueArry[curr] = strdup(userStr);
        curr++;
    }
    fclose(fp);
    for (int i = 0; i &lt; curr; i++) {
        printf(&quot;%d - %s \n&quot;, keyArry[i], &amp;valueArry[i]);
    }
    return 0;
}

huangapple
  • 本文由 发表于 2023年3月12日 07:21:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75710181.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定