c - 在函数之间传递 char 指针 - 两种方式是否相等? - C

标签 c pointers char

我已经完成了一个将 char 指针传递给其他函数的 MCVE 代码。如果两种传递 char 指针参数的方式相等(str1str2 如何传递到 passingCharPointer1passingCharPointer2 恭敬地)。

此外,我在代码中包含了注释,其中包含自由/空函数的行为及其行为(如果也有人阅读,我将不胜感激)。

代码是:

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

#define MAX_LENGTH 50

void passingCharPointer1(char *str) {
    strcpy(str, "Hi-1!");
}

void passingCharPointer2(char **str) {
    strcpy(*str, "Hi-2!");
}



int main() {
    // Init char pointers
    char *str1 = malloc((MAX_LENGTH +1)*sizeof(char));
    char *str2 = malloc((MAX_LENGTH +1)*sizeof(char));

    // Gets their values
    printf("Input string 1: ");
    fgets(str1, MAX_LENGTH , stdin);
    printf("Input string 2: ");
    fgets(str2, MAX_LENGTH , stdin);
    printf("\n");

    // Remove '\n' character
    str1[strcspn(str1, "\n")] = '\0';
    str2[strcspn(str2, "\n")] = '\0';

    // Print their values
    printf("BEFORE - Function 1: %s\n", str1);
    printf("BEFORE - Function 2: %s\n", str2);

    // Pass to function in two ways - ARE BOTH WAYS EQUAL?
    passingCharPointer1(str1);
    passingCharPointer2(&str2);

    // Print their values
    printf("AFTER - Function 1: %s\n", str1);
    printf("AFTER - Function 2: %s\n", str2);

    // Freeing pointers
    free(str1);
    free(str2);

    // Print their values after freeing
    printf("\nAFTER FREE 1: %s\n", str1); // Show rare characters (I supposse it is normal behaviour after free)
    printf("AFTER FREE 2: %s\n", str2); // Continue having its content (I supposse it is not normal behaviour after free)

    // Nulling pointers
    str1 = NULL;
    str2 = NULL;

    // Print their values after nulling
    printf("\nAFTER NULL 1: %s\n", str1); // Normal behaviour
    printf("AFTER NULL 2: %s\n", str2); // Normal behaviour

    // Exit success
    return 0;
}

最佳答案

一般来说,这两个函数是不等价的。第一个函数按值接受指针,而第二个函数按引用接受指针。因此,第二个函数可以更改表达式中用作参数的原始指针。

考虑以下演示程序

#include <stdio.h>

void passingCharPointer1( char *s ) 
{
    s = "Bye";
}

void passingCharPointer2( char **s )
{
    *s = "Bye";
}

int main(void) 
{
    char *s1 = "Hello";
    char *s2 = "Hello";

    printf( "Before function calls: %s %s\n", s1, s2 );

    passingCharPointer1( s1 );
    passingCharPointer2( &s2 );

    printf( "After function  calls: %s %s\n", s1, s2 );

    return 0;
}

它的输出是

Before function calls: Hello Hello
After function  calls: Hello Bye

注意在释放内存后访问内存会调用未定义的行为。

关于c - 在函数之间传递 char 指针 - 两种方式是否相等? - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49718220/

相关文章:

java - 我正在尝试将二维字符数组初始化为空格,但控制台中的输出很奇怪

c - memcpy() 是否使用 realloc()?

c - 使用写函数打印程序的参数

c++ - 指向数组的指针给 C++ 带来麻烦

c - 在 C 中将 strcpy 与字符串数组一起使用

wpf - 文本框密码字符

c++ - 在 UDP 套接字中使用 Connect()、send()、recv 时出现问题

c - 返回复合文字

更改指针时 C++ 指针中断

C++双指针未知转换