简体   繁体   English

如何使用 C 中的方法将 int 分配给 int*?

[英]How to assign an int to an int* with a method in C?

I made a method that receives an int* and this value will be assign to another int*.我做了一个接收 int* 的方法,这个值将分配给另一个 int*。 When I call the method, I put an integer but I receive the error of conversion.当我调用该方法时,我输入了一个整数,但收到了转换错误。

I try to cast the int with (int*) but the program crashes.我尝试使用 (int*) 转换 int 但程序崩溃了。

add(hashTable,  8, 0);

void add(hash_table *hashTable, int *num, int value)

How can I assign an integer value to an int* in a method?如何在方法中为 int* 分配整数值?

First, you should understand what int * means.首先,您应该了解int *含义。 It means you have an int somewhere in memory, and rather than copying the value of that int into a function, you pass in the address of that variable.这意味着您在内存中的某处有一个 int,而不是将该 int 的值复制到函数中,而是传入该变量的地址。 You can't pass in the address of a variable until you first have a variable.在您首先拥有一个变量之前,您无法传入变量的地址。 So the simple solution is to create a variable and give that variable the value you want.因此,简单的解决方案是创建一个变量并为该变量指定您想要的值。 Then you can just pass in the address of that variable.然后你可以传入那个变量的地址。

int n = 8;
add(hashTable, &n, 0);

int's are integer values, and int * is a pointer to an integer. int 是整数值,而 int * 是指向整数的指针。 In other words, int * is a location in memory that points to your integer.换句话说, int * 是内存中指向整数的位置。 In order to to assign an int to an int *, you need to put the int into the memory location pointed to by int *.为了给一个int *分配一个int,你需要把这个int放入int *所指向的内存位置。 To do this, you simply put the integer at the memory location pointed to by int * (assuming the memory is already allocated)为此,您只需将整数放在 int * 指向的内存位置(假设内存已分配)

 int *my_pointer = (int *)malloc(sizeof(int));  // allocate memory 
 *my_pointer = my_val;

(you must allocate memory here, or it will crash) (必须在这里分配内存,否则会崩溃)

or或者

 int my_val = 8;  // the memory is allocated here, so you are safe
 int *my_pointer = &my_val;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM