Reputation: 74
I've a problem when I run the program which is:
invalid operands to binary - (have 'int' and 'int *')
Since I defined a dynamic array **engelCikacagiYer
then I tried to make an operation on karakterHP
int karakterHP = 100;
int **engelCikacagiYer;
engelCikacagiYer = malloc(engelSayisi * sizeof(int));
for(i = 0; i < engelSayisi; i++){
engelCikacagiYer[i] = (rand() % (100 - 5 + 1) + 5);
}
for(i = parkurUzunlugu.Baslangic; i < parkurUzunlugu.Bitis; i++){
if (asal(engelCikacagiYer)) {
karakterHP -= engelCikacagiYer[i];
printf("%d\t", karakterHP);
}
}
Upvotes: 0
Views: 407
Reputation:
Change int **engelCikacagiYer;
to int *engelCikacagiYer;
.
By your code it seems you want a dynamic array of ints, not a dynamic array of int pointers.
Upvotes: 2
Reputation: 23802
This piece of code:
int **engelCikacagiYer;
engelCikacagiYer = malloc(engelSayisi*sizeof(int));
Is not correct, to allocate memory to a double pointer, aka pointer to pointer you need to allocate using the size it points to and that is pointer to int
so you would need:
engelCikacagiYer = malloc(engelSayisi*sizeof(int*));
Or better yet:
engelCikacagiYer = malloc(engelSayisi*sizeof(*engelCikacagiYer));
Later you try to assign an int
value to a engelCikacagiYer[i]
which is a pointer variable not an int
variable, hence the error.
If you really need a double pointer, after the first malloc
you will need to allocate memory for each engelCikacagiYer[i]
pointer:
for(int i = 0; i < engelSayisi; i++){
engelCikacagiYer[i] = malloc(sizeof(**engelCikacagiYer));
}
And assing values as if it was a 2D array (I mean using the same notation), example:
engelCikacagiYer[i][0] = (rand()%(100-5+1)+5);
or
*engelCikacagiYer[i] = (rand()%(100-5+1)+5);
Here is a simplified possible implementation of a correct allocation:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int **engelCikacagiYer;
engelCikacagiYer = malloc(100 * sizeof(*engelCikacagiYer)); //check allocation for errors
for(int i = 0; i < 100; i++){
engelCikacagiYer[i] = malloc(sizeof(**engelCikacagiYer)); //check allocation
*engelCikacagiYer[i] = (rand() % (100 - 5 + 1) + 5);
}
for (int i = 0; i < 100; i++) //test print
{
printf("%d ", *engelCikacagiYer[i]);
}
}
In any case, for the code you present using a single pointer to int
would also be a valid (and simpler) solution.
Upvotes: 2