[英]warning: assignment makes pointer from integer without a cast [-Wint-conversion] p = (i + 1) * 100;
I am trying to fill array with the numbers without using scanf
.我正在尝试用数字填充数组而不使用
scanf
。 I encountered warning: assignment makes pointer from integer without a cast [-Wint-conversion]
我遇到警告:
assignment makes pointer from integer without a cast [-Wint-conversion]
p = (i + 1) * 100;
^
and when i try to print the array the array output random values.当我尝试打印数组时,数组 output 随机值。 How do i solve it?
我该如何解决?
#include<stdio.h>
int main() {
int nums[8], i;
int *p;
p = nums;
for (int i = 0; i < 8; ++i)
{
p = (i + 1) * 100;
p++;
}
return 0;
}
You declared a pointer你声明了一个指针
int *p;
p = nums;
and then instead of assigning the element of the array pointed to by the pointer you are trying to assign the pointer itself with an integer value.然后不是分配指针指向的数组元素,而是尝试为指针本身分配 integer 值。
p = (i + 1) * 100;
It is evident that you mean很明显你的意思是
*p = (i + 1) * 100;
Pay attention to that it is a bad idea to use the magic number 8
in the for loop.请注意,在 for 循环中使用幻数
8
是个坏主意。 It is better to use a named constant.最好使用命名常量。
If you want to fill the array using a pointer in the for loop then the program can look the following way如果要在 for 循环中使用指针填充数组,则程序可以如下所示
#include<stdio.h>
int main( void )
{
enum { N = 8 };
int nums[N];
int init_value = 1;
for ( int *p = nums; p != nums + N; ++p )
{
*p = 100 * init_value++;
}
return 0;
}
Using this approach you can write a separate function that will initialize an array the following way使用这种方法,您可以编写一个单独的 function ,它将按以下方式初始化数组
void init_array( int *a, size_t n, int value )
{
for ( int *p = a; p != a + n; ++p )
{
*p = 100 * value++;
}
}
In the assignment p = (i + 1) * 100
, p
is an int *
, not an int
, so the assignment would convert the integer (i + 1) * 100
to a pointer.在赋值
p = (i + 1) * 100
中, p
是int *
,而不是int
,因此赋值会将 integer (i + 1) * 100
转换为指针。 Instead, use *p = (i + 1) * 100
.相反,使用
*p = (i + 1) * 100
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.