C - 传递和操作 char 指针和指针到指针

C - Pass and operate on char pointers and pointer-to-pointer

作为C语言的新手,我正在和指针作斗争,特别是双指针。

我的意图是

  1. main
  2. 中的 malloc 字符指针
  3. 将分配的指针传递给不同的函数
  4. 获取同一指针内每个函数的结果
  5. 释放 main
  6. 中的指针

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

void process1(char **pointer) {
    //this should take and change the pointer value from a to x
    (*pointer)[0] = 'x';
    (*pointer)[1] = '[=10=]';
}

void process2(char **pointer) {
    //this should take the pointer, free and NULL it, do a new malloc and set the pointer value to y
    char* p = *pointer;
    free(p);
    p = NULL;

    p = malloc(sizeof(char)*2);
    p[0] = 'y';
    p[1] = '[=10=]';

    *pointer = p;
}

void main() {
    char* p = malloc(sizeof(char)*2);
    p[0] = 'a';
    p[1] = '[=10=]';
    //should print a
    printf("%s\n",p);
    process1(&p);
    //should print x
    printf("%s\n",p);
    process2(&p);
    //should print y
    printf("%s\n",p);

    free(p);
    p=NULL;

}

//this is the Output as expectd
sh-4.2$ main
a
x
y

我现在的问题是:

  1. 这是好的做法吗?
  2. 分配 p 指针时,我是否在函数 process2 中泄漏了内存?我需要在某处释放这个 p 指针吗?
  1. Is this good practice?
  • 当您不知道在编译时将接收多少输入数据时,动态内存很有用。您可以轻松地重新分配动态数组的大小,而不能修改堆栈上的数组大小。

  • 最大的缺点是内存泄漏和可能的分段错误。

  • 你必须free分配内存。

  • 自动存储上声明的数组更易于使用且速度更快

在您的情况下无需将指针传递给指针,只需使用

void process1(char *pointer) {
    pointer[0] = 'x';

process1(p);

在进程 2 中,您可以使用 realloc() 而不是释放和分配新内存。以免建议 pointerchar*.

pointer = realloc (pointer, 4 * sizeof(int));
  • 您不会丢失已存储在 pointer 数组中的数据

  1. Am I leaking memory in the function process2 when mallocing the p pointer?

不,没有任何内存泄漏或越界。


如果您正在使用指针,最好使用名为 valgrind.

的工具调试您的程序

如果您不必使用 动态分配,请不要。它容易出错,速度较慢,您必须释放数据。

这个程序运行良好。它正确地释放了所有分配的内存,并且不会在分配的内存范围之外写入。

从重新分配先前分配的内存的角度来看,process2 所做的很好。在这种特殊情况下,您分配的内存量与以前相同,但一般来说,如果这样的函数可能会扩展分配的内存,那么传递一个双指针来修改调用函数中的指针变量是有意义的。

至于process1,address传入的指针并没有被修改,只是指向什么,所以这里不需要双指针。您可以将其定义为:

void process1(char *pointer) {
    pointer[0] = 'x';
    pointer[1] = '[=10=]';
}

并这样称呼它:

process1(p);
  1. 在函数中释放内存不是一个好主意,除非您 100% 确定传递的指针已分配。否则,如果您忘记它并传递任何其他指针,它非常容易出错。

  2. 你的函数

void process1(char **pointer) {
    //this should take and change the pointer value from a to x
    (*pointer)[0] = 'x';
    (*pointer)[1] = '[=10=]';
}

不需要char **参数

void process1(char *pointer) {
    //this should take and change the pointer value from a to x
    pointer[0] = 'x';   // or *pointer = 'x';          or *pointer++ = 'x';
    pointer[1] = '[=11=]';  // or *(pointer + 1) = '[=11=]';   or *pointer = '[=11=]';
}