I am trying to fill array with the numbers without using scanf
. I encountered warning: 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. 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;
}
CodePudding user response:
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.
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. 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
#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
void init_array( int *a, size_t n, int value )
{
for ( int *p = a; p != a n; p )
{
*p = 100 * value ;
}
}
CodePudding user response:
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. Instead, use *p = (i 1) * 100
.