I have to make a program which asks me to enter different values and then it has to print them on the screen. Aftar that, It asks me, "which value of the vector you want to change?" and I have to enter the number of the value and than the value itsself.
When I run the program I get several warnings like this:
"warning: format '%d' expects argument of type 'int', but argument 6 has type 'int *' [-Wformat=]"
I don't know how to fix this, I tried using %p but it doesn't help. Any ideas?
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
int main()
{
int intero = 0;
int *p_int;
int vettore[MAX] = {0};
int *p_vet;
int num = 0;
int val = 0;
char carattere = 0;
char *p_car;
p_int = &intero;
p_car = &carattere;
p_vet = vettore;
printf("Enter an integer: ");
scanf ("%d", &intero);
fflush (stdin);
printf ("\nEnter a character: ");
scanf("%c", &carattere);
fflush (stdin);
for (int i=0; i<MAX; i++)
{
printf("\nEnter integer n^%d of the vector: ", i);
scanf("%d", &vettore[i]);
fflush (stdin);
}
printf("\n\n\n");
printf("Type\t\tDirect Value\t\tValue by Pointer\tDirect Position\tPosition by Pointer\n");
printf("__________________________________________________________________________________________________________________\n\n");
printf("Integer:\t\t%d\t\t\t%d\t\t\t\t%d\t\t\t\t%d\n\n", intero, *p_int, &intero, p_int);
printf("Character:\t%c\t\t\t%c\t\t\t\t%d\t\t\t\t%d\n\n", carattere, *p_car, &carattere, p_car);
for (int i=0; i<MAX; i++)
{
printf("Integer n^%d:\t%d\t\t\t%d\t\t\t\t%d\t\t\t\t%d\n\n", i, vettore[i], *p_vet, &vettore[i], p_vet);
p_vet++;
}
p_vet = vettore;
printf("\nEnter which value of the vector you want to change: ");
scanf("%d", &num);
fflush(stdin);
printf("\nEnter now the value you want: ");
scanf("%d", &val);
fflush(stdin);
*(p_vet + num) = val;
printf("\n\n");
for (int i=0; i<MAX; i++)
{
printf("Integer n^%d:\t%d\t\t\t%d\t\t\t\t%d\t\t\t\t%d\n\n", i, vettore[i], *p_vet, &vettore[i], p_vet);
p_vet++;
}
return 0;
}
By using %p
format specifier, you're telling printf that the value you're trying to print is actually a memory address, not the value the pointer points to. Whenever you use a pointer without dereferencing it with *
operand, you're just printing the memory offset it points to, which isn't formatted as integer. It seems to me that sometimes you just do that, like here: printf("Integer:\t\t%d\t\t\t%d\t\t\t\t%d\t\t\t\t%d\n\n", intero, *p_int, &intero, p_int);
Since p_int
is a pointer and you're using %d
as format specifier, it throws you that kind of error. Dereferencing it with *p_int
is the right thing to do, I think, unless your intention is to actually print the memory offset, in that case you should use %p
and cast the pointer to (void*)
.