我已经完成了一个将 char 指针传递给其他函数的 MCVE 代码。如果两种传递 char 指针参数的方式相等(str1
和 str2
如何传递到 passingCharPointer1
和 passingCharPointer2
恭敬地)。
此外,我在代码中包含了注释,其中包含自由/空函数的行为及其行为(如果也有人阅读,我将不胜感激)。
代码是:
#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/