当尝试使用函数交换 2 个指针的值来反转数组时,核心不断转储
#include<stdio.h>
int main() {
/* read integer array */
int n, i;
scanf("%d", &n);
int *a = (int *)malloc(n * sizeof(int));
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
/* reverse the array */
for (i = 0; i < n / 2; i++) {
exchange(a[i], a[n - i - 1]);
}
/* print the array */
for (i = 0; i < n; i++) {
printf("%d ", a[i]);
}
/* free the memory */
free(a);
return;
}
/* write a function that takes two pointers of two intergers and then exchanges the values
in those locations */
void exchange(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
这是代码,函数交换尝试交换这两个指针指向的整数的值。 不断地倾倒核心。
#include<stdio.h>
int main() {
/* read integer array */
int n, i;
scanf("%d", &n);
int *a = (int *)malloc(n * sizeof(int));
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
/* reverse the array */
for (i = 0; i < n / 2; i++) {
exchange(a[i], a[n - i - 1]);
}
/* print the array */
for (i = 0; i < n; i++) {
printf("%d ", a[i]);
}
/* free the memory */
free(a);
return;
}
/* write a function that takes two pointers of two intergers and then exchanges the values
in those locations */
void exchange(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
This is the code, the function exchange tries to exchange the values of the integers which these two pointers are pointing to.
Keeps dumping the core.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在此函数交换调用中,
两个参数的类型均为
int
,而函数需要的参数类型为int *
。您需要像这样调用该函数
In this call of the function exchange
the both arguments have the type
int
while the function expects arguments of the typeint *
.You need to call the function like
您需要发送交换函数的地址值,因为它的参数被声明为指针。因此,您需要将此行更改
为此行,因为正如我提到的,它需要地址。
You need to send address values for exchange functions since arguments of it are declared as pointers. Therefore, you need to change this line
to this line because as I mentioned it expects addresses.
更好的方法是将整个数组和索引传递给交换。
像这样:
在线尝试
A nicer way would be passing the whole array and indexes to swap.
Like this:
TRY IT ONLINE