简体   繁体   English

字符指针 Malloc/Realloc

[英]Char Pointer Malloc/Realloc

What I'm trying to do is a small program that takes a suite of numbers (123654000256 per example) and deletes all the numbers after detecting a '0' (should return 123 if I enter 1230456), so I'm trying to do it with malloc / realloc but when I realloc it still returns all the elements我正在尝试做的是一个小程序,它采用一组数字(每个示例为 123654000256)并在检测到“0”后删除所有数字(如果我输入 1230456,则应返回 123),所以我正在尝试做它与 malloc / realloc 但当我重新分配它仍然返回所有元素

#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;
}

I enter 4564560123 it returns it as I entered it, whats the prob ?我输入 4564560123 它在我输入时返回它,这是什么问题?

You need to realloc space for a + 1 to fit the null terminator, then null terminate the string, suite[a] = '\\0' .您需要为 a + 1 重新分配空间以适合空终止符,然后空终止字符串suite[a] = '\\0'


Why this bug gave you the whole sequence of numbers:为什么这个错误给了你完整的数字序列:

Once you call realloc, it just means that the system is free to use the remaining parts of the previously allocated memory for other purposes.一旦调用了 realloc ,就意味着系统可以自由地将之前分配的内存的剩余部分用于其他目的。 There is no such thing as "deleting" memory, it just gets invalidated and the old data will remain in those memory cells until used for other purposes.没有“删除”内存这样的事情,它只是变得无效,旧数据将保留在这些内存单元中,直到用于其他目的。

So if you forget null termination and the system has not yet used that memory, the old data remains there and that's why you get the full sequence as output.因此,如果您忘记了空终止并且系统尚未使用该内存,则旧数据仍保留在那里,这就是您获得完整序列作为输出的原因。 There is no guarantee that you would get the old data though - the program could as well crash.但是不能保证您会获得旧数据 - 程序也可能崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM