【发布时间】:2021-03-13 11:13:22
【问题描述】:
我无法理解使用指针的目的。下面的代码是使用指针打印给定字符串的所有排列。
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
void swap(char *p1, char *p2) {
char pmt;
pmt = *p1;
*p1 = *p2;
*p2 = pmt;
}
void permutation(char *str, int index,int n ) {
int i;
if (index == n) {
printf("%s ", str);
}
else {
for (i = index; i<=n; i++) {
swap((str+index), (str+i));
permutation(str, index+1, n);
swap((str+index), (str+i));
}
}
}
int main() {
char s[] = "ABCD";
int n = strlen(s);
permutation(s, 0, n-1);
printf("\n\n");
return 0;
}
如果我要删除指针,我的交换函数现在将变为
void swap(char p1, char p2) {
char pmt;
pmt = p1;
p1 = p2;
p2 = pmt;
}
我仍然会得到与带有指针的输出相同的输出。但是,需要注意的是我的输出会产生一些警告
grok1.c:23:6: warning: incompatible pointer to integer conversion passing 'char *' to parameter of type 'char'; dereference with * [-Wint-conversion]
swap((str+index), (str+i));
^~~~~~~~~~~
*
grok1.c:10:16: note: passing argument to parameter 'p1' here
void swap(char p1, char p2) {
^
grok1.c:23:19: warning: incompatible pointer to integer conversion passing 'char *' to parameter of type 'char'; dereference with * [-Wint-conversion]
swap((str+index), (str+i));
^~~~~~~
*
grok1.c:10:25: note: passing argument to parameter 'p2' here
void swap(char p1, char p2) {
^
grok1.c:25:6: warning: incompatible pointer to integer conversion passing 'char *' to parameter of type 'char'; dereference with * [-Wint-conversion]
swap((str+index), (str+i));
^~~~~~~~~~~
*
grok1.c:10:16: note: passing argument to parameter 'p1' here
void swap(char p1, char p2) {
^
grok1.c:25:19: warning: incompatible pointer to integer conversion passing 'char *' to parameter of type 'char'; dereference with * [-Wint-conversion]
swap((str+index), (str+i));
^~~~~~~
*
grok1.c:10:25: note: passing argument to parameter 'p2' here
void swap(char p1, char p2) {
4 warnings generated.
ABCD ABCD ABCD ABCD ABCD ABCD ABCD ABCD ABCD ABCD ABCD ABCD ABCD ABCD ABCD ABCD ABCD ABCD ABCD ABCD ABCD ABCD ABCD ABCD
如果有人可以帮助解释这些警告,我将不胜感激,因为我在这里有点挣扎。谢谢!
【问题讨论】:
-
您的交换版本将无效。您实际上可以对其进行测试以反驳您的假设。
-
如果您更改函数的签名(参数的数量和类型以及返回类型),您还必须更改调用方式:
swap(str[i], str[j])。但如前所述,该函数交换两个局部变量,不会对您的排序产生任何影响。 -
不管你怎么说,你的输出和非指针代码不一样。它是 ABCD 重复 24 次,而之前都是排列。
标签: c pointers permutation