带指针的 C 函数在一台计算机上工作,在另一台计算机上不起作用

C function with pointers work on one computer, and doesn't work on another

#include <stdio.h>
void swap (int *a, int *b)
 {
    int *tmp;
    *tmp = *a;
    *a = *b;
    *b = *tmp;
 }

int main ()
{
 int x = 5;
 int y = 7;
 swap (&x,&y);
 printf ("\n x = %d \n y = %d \n",x,y);
}

我正在使用 codeblocks,但这段代码无法运行,我不明白为什么...在一台计算机上它运行良好,但在另一台计算机上它根本无法运行 运行 . 有什么帮助吗? 提前致谢。

int tmp;
tmp = *a;
*a = *b;
*b = tmp;

您需要的是一个变量 tmp 来存储值,而不是指针 *tmp

下面的代码确实是一种糟糕的方法,但是

int *tmp = malloc(sizeof(int));

    *tmp = *a;
    *a = *b;
    *b = *tmp; 

完成后请使用

释放内存
free(tmp);

Gopi 已经更正了您的代码 - 添加到以前的答案 - 我认为这对新手来说是很好的信息:

第 4.1 节指出:

An lvalue (3.10) of a non-function, non-array type T can be converted to an rvalue. If T is an incomplete type, a program that necessitates this conversion is ill-formed. If the object to which the lvalue refers is not an object of type T and is not an object of a type derived from T, or if the object is uninitialized, a program that necessitates this conversion has undefined behavior. If T is a non-class type, the type of the rvalue is the cv-unqualified version of T. Otherwise, the type of the rvalue is T.

当您尝试取消引用和未初始化的指针时,行为未定义。未定义意味着任何事情都可能发生——没有保证。所以你可以在不同的环境中获得不同的行为。

来自维基Making pointers safer

A pointer which does not have any address assigned to it is called a wild pointer. Any attempt to use such uninitialized pointers can cause unexpected behavior, either because the initial value is not a valid address, or because using it may damage other parts of the program. The result is often a segmentation fault, storage violation or wild branch (if used as a function pointer or branch address).

你在这里做了什么:

int *tmp;
*tmp = *a;

是你创建了一个指向 int 的指针,它没有指向任何东西 - 基本上它包含一些垃圾值(甚至可能是你的密码 - 谁知道)。

如果你想使用指针,虽然它根本没有任何意义

void swap(int *a, int *b)
{
    int tmp[1];

    *tmp = *a;
    *a   = *b;
    *b   = *tmp;
}

这里的tmp严格来说不是指针,但是可以在上面使用*间接运算符

void swap(int *a, int *b)
{
    int value = *a;
    int *tmp  = &value;

    *tmp = *a;
    *a   = *b;
    *b   = *tmp;
}

或者你可以使用 malloc 正如 Gopi 已经指出的那样。

你的错误是使用了未初始化的内存。在使用指针之前始终将内存分配给它。接下来,不要忘记在完成分配后释放分配的内存。

此外,您应该在 main() 函数的末尾添加 return 0;

如果您不介意第二个意见,请检查以下代码。

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

void swap (int *a, int *b)
{
        int *tmp = malloc(sizeof(*tmp));
        *tmp = *a;
        *a = *b;
        *b = *tmp;
        free(tmp);
}

int main ()
{
        int x = 5;
        int y = 7;
        swap (&x,&y);
        printf ("\n x = %d \n y = %d \n",x,y);
        return 0;
}

如果你想使用指针,那就使用指针:

#include <stdio.h>

void swap (int ** ppx, int ** ppy)
 {
   int * p = *ppx;
   *ppx = *ppy;
   *ppy = p;
 }

int main (void)
{
  int x = 5;
  int y = 7;
  int * px = &x;
  int * py = &y;

  printf ("\nx = %d\ny = %d\n", *px, *py);

  swap (&px, &py);

  printf ("\nx = %d\ny = %d\n", *px, *py);

  return 0;
}

结果:

x = 5
y = 7

x = 7
y = 5