I'm learning C, malloc and pointers specifially, I'm testing this code:
#include<stdio.h>
#include<stdlib.h>
int main(){
char test[5] = "ayolw";
printf(" \nmy string : %s\n", test);
char *testa = (char *)malloc(sizeof(char));
testa = test;
printf("%c", *testa);
printf("%c", *testa 1);
printf("%c", *testa 2);
printf("%c", *testa 3);
printf("%c\n", *testa 4);
while(*testa!='\0'){
printf("%c ", *testa);
*testa ;
}
printf("\n\n");
return 0;
}
My output:
my string : ayolw
abcde // output using *testa 1,*test 2,...;
a y o l w // output using *testa ;
I understand my first output are returning testa[0] ASCII value number. howhever why using *testa are returning correctly if testa is equivalent to testa 1
And another question, how can I print my output using a lign like *testa 2 if I can't use testa[2]. That its possible?
CodePudding user response:
howhever why using *testa are returning correctly if testa is equivalent to testa 1
Because testa is not equivalent to testa 1. Not even very close. It differs in several significant regards, among them:
testaevaluates to the value oftesta, and as a side effect, modifiestesta's stored value, increasing that by 1. On the other hand,testa 1evaluates to one more than the value oftestaand does not modifytesta's stored value.The postfix
operator has higher precedence than unary*, whereas the binaryoperator has lower precedence than unary*. That means that*testa 1is equivalent to(*testa) 1, whereas*testais equivalent to*(testa ).
Taking these together,
the value of
testadoes not change in the various*testa xcases. It always points at the first character oftest, and the*testapart always evaluates to the value of that character. The addition is applied to that character value (promoted to anint).the value of
testadoes change in the various*testacases. Each evaluation of that expression returns the character to whichtestacurrently points, and also updatestestato point to the next character.
As a separate matter, note that in ...
char *testa = (char *)malloc(sizeof(char)); testa = test;
...
you do not need to cast the return value of
malloc()in C, nor should you.that particular
malloc()is wasteful, as you immediately replace the only pointer to the allocated memory with a pointer to the first byte of arraytest. The dynamically allocated memory is leaked. Better would be any ofchar *testa; testa = test;OR
char *testa = test;OR
char *testa; testa = &test[0];OR
char *testa = &test[0];, all of which are equivalent to each other for your definition of
testas an array ofchar.
CodePudding user response:
First of all, you don't have testa and testa 1, you have *(testa ) vs (*testa) 1. Notice that you are adding one to different things.
Secondly, x is NOT equivalent to x 1. x is closer, but it's not equivalent either.
x evaluates to the original value of x. Assigns x plus 1 to x.
x 1 evaluates to x plus 1. Does not modify x.
x evaluates to x plus 1. Assigns x plus 1 to x.
