我有这段代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 3
void AddName(char *Names[],int *size)
{
char str[100];
int len;
if (*size < MAX)
{
printf("Enter a string: ");
scanf(" %s", &str);
len = strlen(str);
Names[*size] = (char *)malloc(len*sizeof(char));
Names[*size] = str;
*size = *size+1;
}else printf("Full Memory!!\n");
}
void PrintNames(char *Names[],int size)
{
int i;
for (i = 0; i<size; i++)
{
printf(" %s\t", Names[i]);
}
printf("\n");
}
main()
{
char *Names[MAX];
int size = 0;
int c;
do
{
printf("=========================\n");
printf("1- Add a new name.\n");
printf("2- Print names.\n");
printf("3- Exit.\n");
printf("=========================\n");
printf("Enter your choice: ");
scanf("%i", &c);
printf("=========================\n");
switch(c)
{
case 1: AddName(Names,&size);
break;
case 2: PrintNames(Names,size);
break;
case 3: printf("Good bye.\n");
break;
default: printf("ERROR: Bad input.\n");
}
}while(c != 3);
}
输入字符串后,当我使用函数printNames(Names,size)
打印它时,它会输出:
=========================
1- Add a new name.
2- Delete an old name.
3- Print names.
4- Exit.
=========================
Enter your choice: 1
=========================
Enter a string: John
=========================
1- Add a new name.
2- Delete an old name.
3- Print names.
4- Exit.
=========================
Enter your choice: 1
=========================
Enter a string: Carl
=========================
1- Add a new name.
2- Delete an old name.
3- Print names.
4- Exit.
=========================
Enter your choice: 3
=========================
):wç0@ ):wç0@
=========================
1- Add a new name.
2- Delete an old name.
3- Print names.
4- Exit.
=========================
Enter your choice:
有什么问题?我以为它可能会丢失&#39; \ 0&#39;但是我如何添加到数组Names
中的每个字符串?
此外,如果我尝试释放或删除其中一个字符串,它会变成垃圾。这是代码:
`
void RemoveName(char *Names[],int *size)
{
int loc;
if (*size > 0)
{
printf("Starting from 0. Enter the name's location: ");
scanf("%i", &loc);
free(Names[loc]);
}
`
答案 0 :(得分:2)
您没有为空终止符分配内存:
len = strlen(str);
Names[*size] = (char *)malloc((len+1)*sizeof(char));
^
然后你覆盖指针,而不是复制字符串:
Names[*size] = str; //pointer to allocated memory is lost
应该是这样的:
strcpy( Names[*size] , str ) ;
代码中还有其他问题,您可以从这开始。
答案 1 :(得分:2)
您的代码中有undefined behavior。首先通过malloc
向指针分配内存,但是在覆盖指针之后直接将其指向本地数组,并且所有其他局部变量一旦超出范围,它将超出范围函数返回,留下一个悬空指针。
答案 2 :(得分:1)
scanf(" %s", &str);
应该是
scanf(" %s", str);
不需要malloc
暂时可能会想到其他一些问题
修改强>
缺少为空字符添加空格并使用strcpy
编辑2
str也在堆栈上,因此它超出了范围