I'm trying to learn C, more specifically pointers and malloc(). I wrote the following program and need a few clarifications about warning messages I got and the output.
#include<stdio.h>
#include<stdlib.h>
void printem(char *ptr, char loopagain)
{
int i;
for (i = 0; i < loopagain; i++)
{
printf("Found %c at address %c \n",ptr[i],&ptr[i]);
}
return;
}
void initializeblock(char *ptr, char loopagain)
{
int i;
for (i = 0; i < loopagain; i++)
{
ptr[i] = 65+i;
}
return;
}
int main()
{
char neededbytes = 10;
char *p;
p = (char *) malloc(neededbytes * sizeof(char));
if(p==NULL)
{
printf("Error! memory not allocated.");
exit(0);
}
else
{
printem(p,neededbytes);
initializeblock(p,neededbytes);
printem(p,neededbytes);
}
free(p);
}
The first problem I have is I don't get the address of each of the 10 char elements to print out correctly as numbers. Instead of a numbers I get symbols. This is the line of code that prints out the values and addresses.
printf("Found %c at address %c \n",ptr[i],&ptr[i]);
What am I doing wrong?
The second problem is inside the else statement I have the following code
printem(p,neededbytes);
initializeblock(p,neededbytes);
printem(p,neededbytes);
originally I used an & before p but got the following warnings
[Warning] passing argument 1 of 'printem' from incompatible pointer type
[Note] expected 'char *' but argument is of type 'char **'
The examples I found online show that a function expecting a pointer should have the address passed to it, why am I getting the warings when I use
printem(&p,neededbytes);
initializeblock(&p,neededbytes);
printem(&p,neededbytes);
Also, when I allocate a block using malloc()
, is there another way to access/modify the data other than using array brackets, p[i]
?
Is there a way to know the size of the block allocated so I don't have to pass it as an argument in the following line
printem(p,neededbytes);