【问题标题】:Understanding why I need malloc了解为什么我需要 malloc
【发布时间】:2016-02-14 08:56:51
【问题描述】:

我想了解为什么我需要在其中使用 malloc。我的代码的目标是将"]" 和")" 与";" 分开。所以像这样"];" 变成"]" ";" 和");" 变成")" ";"。 ptr 被用作字符串数组。我不记得字符串数组的技术名称。这很有效,但它节省了我很多时间来理解为什么会在未来发生这种情况。

char  *ptr[buflen];
for(x = 0; x < n; x++)
{
    printf("ptr[x] is %s \n", ptr[x]);
    cmp_str3 = strcmp(ptr[x], "];");
    cmp_str4 = strcmp(ptr[x], ");");
    if(cmp_str3 == 0)
    {
        printf("Match1 \n");
        strcpy(str1, ptr[x]);
        printf("Match2 \n");
        ptr[x][1] = '\0';
        printf("Match3 \n");
        //printf("ptr[x+1] %c %d \n", ptr[x+1], ptr[x+1]);
        //printf("ptr[x+1][0] %c %d \n", ptr[x+1][0], ptr[x+1][0]);
        ptr[x+1] = malloc(strlen("foo") + 1);
        ptr[x+1][0] = str1[1];
        printf("Match4 \n");
        ptr[x+1][1] = '\0';
        printf("Match5 \n");
        n++;
    }
    if(cmp_str4 == 0)
    {
    }
}
cmp_str3 = 0;
cmp_str4 = 0;
memset(str1, 0, 15);
memset(str2, 0, 15);

【问题讨论】:

  • 所以你是说你写了这段代码,从那时起你就忘记了为什么需要使用 malloc,你现在想弄清楚你写这段代码的时候在想什么?
  • ptr 是一个指针数组。尝试取消引用未初始化的指针会导致未定义的行为。
  • 这就是为什么你应该注释你的代码,所以你知道你的意图lendemain。
  • 哦...........只是没有。
  • 在这种情况下,如果您删除这两条注释行以及所有其他多余的printfs,将会有所帮助。然后你可能会真正看到你的代码在做什么。而malloc(strlen("foo")+1); 是写malloc(4) 的荒谬方式,尤其是当你只需要malloc(2) 时。

标签: c malloc


【解决方案1】:

声明

char *ptr[buflen];

创建一个指针数组。如果ptr 是局部变量(在函数内部),则指针最初是垃圾值,它们不指向有效内存。如果ptr 是全局的或静态的,那么指针最初是NULL。

在任何情况下,在您可以使用其中一个指针指向字符串之前,该字符串需要在内存中的某个位置。

给定的行

char *ptr[3] = {"foo", "bar", "bletch"};

编译器负责为字符串分配内存,然后将指向字符串的指针放入数组中。

但是如果字符串不是常量,那么你必须自己为字符串分配内存。这就是malloc 所做的。它分配您请求的字节数,并返回指向该内存的指针。您可以将该指针保存在数组中,然后使用strcpy 或其他字符串函数将字符串放入该内存中。

或者您可以一次复制一个字符,这就是您的代码所做的:

ptr[x+1] = malloc(2);     // reserves two bytes of memory, and keeps the pointer 
                          // to that memory in the array of pointers
ptr[x+1][0] = str[1];     // copies a character into the first byte of the memory
ptr[x+1][1] = '\0';       // marks the second byte as the end of the string

所以现在你在内存中有一个字符串,并且在指针数组中有一个指向该字符串的指针。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    • 2013-09-07
    • 2011-01-13
    • 2011-04-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多