该函数保存新字符串并将其设置在位置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; }
答案 0 :(得分:0)
您的代码存在两个问题。首先,char名称本质上是一个指针数组。而那些指针.......他们并没有指向分配的内存,只是垃圾数据。如果要充分利用它,则必须为指定的内存分配指针。现在,通常,当您使用像scanf这样的函数时,它们会假定您给它的指针(在本例中为&amp; name [0])已分配内存来存储输入字符串。但是,如果你不这样做,你的指针将指向内存中的随机地址,可能编辑其他一些内存单元并导致程序行为非常奇怪。那你怎么解决这个问题呢?我并没有声称我的解决方案是完美的,但只是使用一个普通的char数组,最好是一个大数组来存储输入字符串。像这样 -
char name[1000];
第二个问题是这一行 -
listf[target] = &name[0];
这里的事情是名称数组指向的数据是临时的。它只会在函数edit()运行时持续。为什么?一个简单的说法是,name属于edit()函数。因此,当edit()终止时,所有内容也随之终止。意思是char名称不会存储你放入它的任何内容。这就是你得到奇怪符号的原因。所以你必须把输入的内容放在内存的另一个地方。所以你必须在这里使用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");
}