C - 指针的正确语法

时间:2015-01-09 20:33:08

标签: c pointers malloc free

我将函数global var调用如下:

char    *Pointer;

然后我把它传递给函数:

char *MyChar = DoSomething (&Pointer);

定义为:

char *DoSomething (char *Destination)
{
   free (*Destination);

   //re-allocate memory
   Destination = malloc (some number);

   //then do something...       

   //finally
   return Destination;
}

只有在我使用(* Destination)而不是(Destination)时它才有效。谁能告诉我这是否正确?我仍然不明白为什么不采取(目的地)。

3 个答案:

答案 0 :(得分:2)

这是正确的,Destination已经被声明为指针,所以你在Destination中传递DoSomething(&Destination)的地址,就像指向指针一样,那么你需要取消引用Destination函数内的DoSomething(),间接运算符*可以为其工作。

但是正确的方法,不是传递指针的地址,而是指针,而不是像

DoSomething(Destination);

现在,因为你想在函数内部使用malloc Destination,你应该这样做

char * DoSomething( char **Destination )
{
   // free( Destination ); why?

   //re-allocate memory
   *Destination = malloc( some number );

   //then do something...       

   //finally
   return *Destination;
}

这是演示如何使用指针

的演示
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

char *copyString(const char *const source)
{
    char *result;
    int   length;

    length = strlen(source);
    result = malloc(length + 1);
    if (result == NULL)
        return NULL;
    strcpy(result, source);

    printf("The address of result is : %p\n", result);
    printf("The content of result is : %s\n", result);
    printf("The first character of result is @ %p\n", &result[0]);

    return result;
}

int main()
{
    char *string = copyString("This is an example");

    printf("\n");

    printf("The address of string is : %p\n", string);
    printf("The content of string is : %s\n", string);
    printf("The first character of string is @ %p\n", &string[0]);

    /* we used string for the previous demonstration, now we can free it */
    free(string);

    return 0;
}

如果你执行上一个程序,你会发现指针都指向同一个内存,并且内存的内容是相同的,所以在free中调用main()将释放内存

答案 1 :(得分:2)

这是一种正确的方法

char    *Pointer;

//,,, maybe allocating memory and assigning its address to Pointer
//... though it is not necessary because it is a global variable and
//... will be initialized by zero. So you may apply function free to the pointer.

char *MyChar = DoSomething( Pointer );


char * DoSomething( char *Destination )
{
   free( Destination );

   //re-allocate memory
   Destination = malloc( some number );

   //then do something...       

   //finally
   return Destination;
}

至于你的代码那么

  1. 参数的类型与函数调用

    中的参数类型不对应

    char * MyChar = DoSomething(&amp; Pointer);

  2. 参数的类型是char *(char * Destination),而参数的类型是 char **(&amp;指针)

    1. 由于Destination是一个指针,而不是

      免费(*目的地);

    2. 你必须写

         free( Destination );
      

答案 2 :(得分:0)

这是因为你传递了一个指针char *Pointer的地址和

char *MyChar = DoSomething (&Pointer);

由于您在函数DoSomething中传入指针的地址,因此它将功能范围变量Destination视为指向地址的指针,该地址是指针Pointer的地址

所以而不是传递Pointer的地址

char *MyChar = DoSomething(&Pointer);

你需要传递指针本身:

char *MyChar = DoSomething(Pointer);

允许您使用

free(Destination);

注意缺少&表示Pointer的地址。

相关问题