通过函数更改数组的值

标签 c arrays pointers

该函数保存新字符串并将其设置在位置 2。但是当我运行最后一个“for”时,出现了一些奇怪的符号。

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


void edit(int target, char *listf[]){

    char *name[1];

    printf("\nInsert the new name: \n");
    scanf("%s", &name[0]);
    listf[target] = &name[0];

    printf("\nThe information has change!\n");
    printf("Name: %s\n", listf[target]);
    system("pause");   }

int main() {
    char *listf[3] = {"Alpha", "Beta", "Omega"};

    int i;
    int target = 2;

    for(i = 0; i < 3; i++){
        printf("%s\n", listf[i]);
    }

    edit(target,listf);
    printf(" \n\n");

    for(i = 0; i < 3; i++){
        printf("%s\n", listf[i]);
    }

    return 0; }

最佳答案

您的代码有两个问题。首先,字符名称本质上是一个指针数组。这些指针……它们并不指向分配的内存,只是垃圾数据。如果你想充分利用它,你必须分配一个指向已分配内存的指针。现在,通常,当您使用像 scanf 这样的函数时,它们会假设您给它的指针(在本例中为 &name[0])已分配内存来存储输入字符串。但如果你不这样做,你的指针将指向内存中的随机地址,可能会编辑其他一些内存单元并导致你的程序行为非常奇怪。那么如何解决这个问题呢?我并不是说我的解决方案是完美的,只是使用一个普通的字符数组(最好是一个大的数组)来存储输入字符串。像这样-

char name[1000];

第二个问题是这一行-

listf[target] = &name[0];

这里的问题是名称数组指向的数据是临时的。它只会在函数 edit() 运行时持续。为什么?简单地说,name 属于 edit() 函数。因此,当 edit() 终止时,所有内容都会随之终止。这意味着 char name 不会存储您放入其中的任何内容。这就是您收到奇怪符号的原因。所以你必须把输入的内容放在内存的另一个地方。所以你必须在这里使用 malloc() 。这是我的编辑功能的固定版本-

void edit(int target, char *listf[]){


char name[1000];

printf("\nInsert the new name: \n");
scanf("%s", name);

//figure out the length of the string and allocate memory accordingly
int len = strlen(name);
char* new_name = malloc(len * sizeof(char));

printf("Test %d\n", len * sizeof(char));

//copy the contents of name to new_name
strcpy(new_name,name);
listf[target] = new_name;

printf("\nThe information has change!\n");
printf("Name: %s\n", listf[target]);
system("pause");

}

关于通过函数更改数组的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47355759/

相关文章:

c++ - 在 C++ 的编译过程中如何在内部表示重载函数

arrays - 按变量值将数组拆分为子数组

c++ - std::shared_ptr 的 use_count 有哪些递增方式?

java - 如果 ArrayList 的大小发生变化,如何从其中选择一个随机元素?

arrays - Cypress 将值推送到 json 数组中

c - 数据类型问题导致值不是 "assignable."可能是指针问题?

C++指针问题

c - 使用 syslog 报告信息

c函数返回两种可能类型之一

c - gsl_matrix_fscanf(文件,矩阵)错误