字符指针 Malloc/Realloc
Char Pointer Malloc/Realloc
我想做的是一个小程序,它接受一组数字(每个示例 123654000256)并在检测到“0”后删除所有数字(如果我输入 1230456,应该 return 123 ), 所以我试图用 malloc / realloc 来做,但是当我重新分配它时它仍然 returns 所有元素
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
char *suite;
int i,a,temp;
suite = (char*)malloc(100*sizeof(char));
printf("Enter a suite of numbers : ");
scanf("%s",suite);
i=-1;
do{
i++;
a=i;
}while((suite[i]-'0') != 0);
suite = realloc(suite,a*sizeof(char));
printf("New suite: ");
printf(suite);
return 0;
}
我输入 4564560123 return我输入的就是这个,有什么问题吗?
您需要为 a + 1 重新分配 space 以适应空终止符,然后以空终止字符串 suite[a] = '[=10=]'
.
为什么这个错误给了你整个数字序列:
一旦你调用realloc,就意味着系统可以自由地使用先前分配的内存的剩余部分用于其他目的。没有 "deleting" 内存这样的东西,它只是失效了,旧数据将保留在那些内存单元中,直到用于其他目的。
因此,如果您忘记了空终止并且系统尚未使用该内存,旧数据将保留在那里,这就是您获得完整序列作为输出的原因。没有保证你会得到旧数据 - 程序也可能崩溃。
我想做的是一个小程序,它接受一组数字(每个示例 123654000256)并在检测到“0”后删除所有数字(如果我输入 1230456,应该 return 123 ), 所以我试图用 malloc / realloc 来做,但是当我重新分配它时它仍然 returns 所有元素
#include <stdio.h>
#include <stdlib.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main(int argc, char *argv[]) {
char *suite;
int i,a,temp;
suite = (char*)malloc(100*sizeof(char));
printf("Enter a suite of numbers : ");
scanf("%s",suite);
i=-1;
do{
i++;
a=i;
}while((suite[i]-'0') != 0);
suite = realloc(suite,a*sizeof(char));
printf("New suite: ");
printf(suite);
return 0;
}
我输入 4564560123 return我输入的就是这个,有什么问题吗?
您需要为 a + 1 重新分配 space 以适应空终止符,然后以空终止字符串 suite[a] = '[=10=]'
.
为什么这个错误给了你整个数字序列:
一旦你调用realloc,就意味着系统可以自由地使用先前分配的内存的剩余部分用于其他目的。没有 "deleting" 内存这样的东西,它只是失效了,旧数据将保留在那些内存单元中,直到用于其他目的。
因此,如果您忘记了空终止并且系统尚未使用该内存,旧数据将保留在那里,这就是您获得完整序列作为输出的原因。没有保证你会得到旧数据 - 程序也可能崩溃。