What is the use of *& in the printf statement and how is the output R?
#include <stdio.h>
int main() {
char* str = "ReplyCodeChallenge";
printf("%c\n", *&*str);
return 0;
}
and the output is: R
This is just a matter of multiple referencing and dereferencing.
str is a string pointer
*str is equivalent to *(str + 0) which is the same as str[0]
&(*str) denotes the address of str[0]
*(&*str) simply dereferences that address and gives str[0] back to you
The brackets don't matter here because both & and * fall under the same precedence group and their associativity is from right to left.
Since str[0] is 'R', that's your output.
By this example, you can conclude that *& or (*&*&...) makes no significant difference. But not always, you may see that syntax used in function headers to receive an argument of pointer-type through pass-by-reference mechanism.
char* str = "ReplyCodeChallenge"; defines str to be a pointer to char and initializes it to point to the first character of "ReplyCodeChallenge". ("ReplyCodeChallenge" is a string literal, which is effectively an array. In this use, it is automatically converted to a pointer to its first element, and that pointer is used as the initial value for str.)
str is a pointer to char, which points to the 'R'.
*str is that char, because * gives the thing that a pointer (an address) points to.
&*str is the address of that char, because & gives the address (a pointer) of a thing.
*&*str is that char, again because * gives the thing that a pointer points to.
There are already enough good answers but I add also mine -- like in any expression, you first of all need to split it in parsing tree, in order to detect the order of evaluation of subexpressions.
*&*str
Here you have 3 applications of 2 unary operators, each of them is
prefix unary-operator. So they have the same precedence, so the parsing tree is like that
(*(&(*str)))
The first application *(str) will return the first character from the beginning of str, which has the same address as str itself. So, &*str will be the address of str. So your applications will reduce to
*str
which is the 1st character (integer that represents the ASCII code) from string.
* - dereferences the object referenced by the pointer
& - gets reference to the object
char *p = "ABCD; - &*p, &*&*p, &*&*&*p, &*&*&*p... - does nothing, it is still reference stored in the pointer.
*&*p, *&*&*p, *&*&*&*p, *&*&*&*p... - just dereferences the char referenced by the pointer p, in this case 'A'
https://godbolt.org/z/ijffmP
The following is the C code:
char *ptr[100];
printf("%s\n",*ptr++);
My question is: we know that array name is not a variable (Ritchie's book "The C programming language" Page 99), so if we define
int *pa,a[5];
This is legal:
pa = a; pa++;
while this is illegal:
a++;
Here char *ptr[100] defines a char pointer array, so ptr represents the initial address of the array. For the above code, if *ptr++ means *(ptr++), this is illegal because array name cannot be used as a variable, and also it's meaningless because *(ptr++) still gets an address as opposed to %s. However, if *ptr++ means (*ptr)++, it also looks strange... Can anyone help to understand this?
The above is my thinking process, my question is: how can *ptr++ give us a string as the code printf("%s\n",*ptr++); says?
Postfix increment ++ has a higher precedence than dereference *.
Thus, *ptr++ is interpreted as *(ptr++). And as you've correctly figured out, ptr++ isn't allowed if ptr is an array (of anything, values or pointers).
If ptr is a pointer, then *ptr++ will indeed increment the pointer (so it will point to the next value after the operation), and this expression will return the current pointed-to value (before increment of the pointer). This expression is indeed sometimes used, e.g. for copying memory areas, e.g.:
while (...) {
*dest++ = *src++; // Copy the current element, then increment both pointers
}
*ptr++ doesn't necessarily give you a string โ it gives you a string if and only if ptr is pointing to a string. And in this case, it's not necessary to post-increment just to get the string โ *ptr would be enough. ++ is done for another purpose.
For example, it ptr is a pointer to an "array" of strings (i.e. a pointer to a pointer to achar, i.e. char **ptr), then you could print all the strings like this:
int i;
for (i = 0; i < N; ++i) {
printf("%s\n",*ptr++); // '++' "jumps" to the next string
}
I believe this link should help you.
C/C++ int[] vs int* (pointers vs. array notation). What is the difference?
The array notation has a bounds limit while the pointer notation does not.
If you wanted to access the next in the array with array notation it would look something like a[n++] n being whatever the current index of the array you are at. Where as assigning ptr to a sets ptr to the first index of the array and you can increment a pointer.
*ptr++ is parsed as *(ptr++) - apply the ++ operator to ptr, then dereference the result.
As written, this results in a constraint violation - ptr is an array of pointers to char, and an expression of array type is a non-modifiable lvalue, and as such may not be the target of an assignment or the operand of the ++ and -- operators.
The line
printf("%s\n",*ptr++);
should (indeed, must) result in the compiler issuing a diagnostic on the order of "invalid lvalue in increment" or something along those lines.
No. 1:
void main(void)
{
int i;
char *ptr[3]={"how","are","you"};
for (i=0;i<3;i++)
printf("%s\n",ptr[i]);
}
This prints out correct answer. Good!
No.2:
void main(void)
{
int i;
char *ptr[3];
*ptr[0] = "how";
*ptr[1] = "are";
*ptr[2] = "you";
for (i=0;i<3;i++)
printf("%s\n",ptr[i]);
}
warning: assignment makes integer from pointer without a cast [enabled by default].....Why can't initialize like this?
No.3:
void main(void)
{
int i;
char *ptr[3]={"how","are","you"};
printf("%s\n",*ptr++);
}
error: lvalue required as increment operand....Why can't we use *ptr++?
#include <stdio.h>
int main()
{
char a[] = "hello";
char *ptr = a;
printf ("%c\n",*ptr++);//it prints character 'h'.
printf ("%c\n",*ptr);//it prints character 'e'.
return 0;
}
As I understand it: In the above code, in *ptr++ expression, both * and ++ have same precedence and operation will take place from right to left, which means pointer will increment first and deference will happen next. So it should print the character 'e' in the first printf statement. But it is not.
So my question is: Where will it store the incremented value (in, *ptr++) if it is not dereferencing that location in first printf statement?
ptr++ means "increment ptr, but return the pre-increment value."
Thus despite the fact that the increment happens first, it is the original, non-incremented pointer that is being dereferenced.
By contrast, if your precedence reasoning is correct, *++ptr should print e as you expect. ++ptr means "increment ptr and return the post-increment value".
Whatever happens is correct.
When doing *ptr ++ it just takes the *ptr value and performs operation as it is a post increment and had you used ++ *ptr it would have printed e in the very first place.
p++ is post increment while ++p is pre increment. p++ gives the values of p and then increments the contents of p while ++p increments the contents of p and then returns the value of p
It will be stored in the pointer ptr itself. It is like making the ptr point to the next byte that it used to point:
ptr = ptr + 1;
yupp, pointer will be autoamticaly incremented after each use.
My question is, what does this code do (from http://www.joelonsoftware.com/articles/CollegeAdvice.html):
while (*s++ = *t++);
the website says that the code above copies a string but I don't understand why...
does it have to do with pointers?
It is equivalent to this:
while (*t) {
*s = *t;
s++;
t++;
}
*s = *t;
When the char that t points to is '\0', the while loop will terminate. Until then, it will copy the char that t is pointing to to the char that s is pointing to, then increment s and t to point to the next char in their arrays.
This has so much going on under the covers:
while (*s++ = *t++);
The s and t variables are pointers (almost certainly characters), s being the destination. The following steps illustrate what's happening:
the contents of t (*t) are copied to s (*s), one character.
s and t are both incremented (++).
the assignment (copy) returns the character that was copied (to the while).
the while continues until that character is zero (end of string in C).
Effectively, it's:
while (*t != 0) {
*s = *t;
s++;
t++;
}
*s = *t;
s++;
t++;
but written out in a much more compact way.
Let's assume s and t are char *s that point to strings (and assume s is at least as large as t). In C, strings all end in 0 (ASCII "NUL"), correct? So what does this do:
*s++ = *t++;
First, it does *s = *t, copying the value at *t to *s. Then, it does s++, so s now points to the next character. And then it does t++, so t points to the next character. This has to do with operator precedence and prefix vs. postfix increment/decrement.
Operator precedence is the order in which operators are resolved. For a simple example, look:
4 + 2 * 3
Is this 4 + (2 * 3) or (4 + 2) * 3? Well, we know it is the first one because of precedence - the binary * (multiplication operator) has higher precedence than the binary + (addition operator), and is resolved first.
In *s++, we have unary * (pointer dereference operator) and unary ++ (postfix increment operator). In this case, ++ has higher precedence (also said to "bind tighter") than *. If we had said ++*s, we would increment the value at *s rather than the address pointed to by s because prefix increment has lower precedence* as dereference, but we used postfix increment, which has higher precedence. If we had wanted to use prefix increment, we could have done *(++s), since the parenthesis would have overridden all lower precedences and forced ++s to come first, but this would have the undesirable side effect of leaving an empty character at the beginning of the string.
Note that just because it has higher precedence doesn't mean it happens first. Postfix increment specifically happens after the value has been used, which his why *s = *t happens before s++.
So now you understand *s++ = *t++. But they put it in a loop:
while(*s++ = *t++);
This loop does nothing - the action is all in the condition. But check out that condition - it returns "false" if *s is ever 0, which means *t was 0, which means they were at the end of the string (yay for ASCII "NUL"). So this loop loops as long as there are characters in t, and copies them dutifully into s, incrementing s and t all the way. When this loop exits, s has been NUL-terminated, and is a proper string. The only problem is, s points to the end. Keep another pointer handy that points to the beginning of s (i.e. s before the while() loop) - that will be your copied string:
char *s, *string = s;
while(*s++ = *t++);
printf("%s", string); // prints the string that was in *t
Alternatively, check this out:
size_t i = strlen(t);
while(*s++ = *t++);
s -= i + 1;
printf("%s\n", s); // prints the string that was in *t
We started by getting the length, so when we ended, we did more pointer arithmetic to put s back at the beginning, where it started.
Of course, this code fragment (and all my code fragments) ignore buffer issues for simplicity. The better version is this:
size_t i = strlen(t);
char *c = malloc(i + 1);
while(*s++ = *t++);
s -= i + 1;
printf("%s\n", s); // prints the string that was in *t
free(c);
But you knew that already, or you'll soon ask a question on everyone's favorite website about it. ;)
* Actually, they have the same precedence, but that's resolved by different rules. They effectively have lower precedence in this situation.
while(*s++ = *t++);
Why do people think it is equivalent to:
while (*t) {
*s = *t;
s++;
t++;
}
*s = *t; /* if *t was 0 at the beginning s and t are not incremented */
when it obviously isn't.
char tmp = 0;
do {
tmp = *t;
*s = tmp;
s++;
t++;
} while(tmp);
is more like it
EDIT: Corrected a compilation error. The tmp variable must be declared outside of the loop.
The aspect that is mysterious about this is the order of operations. If you look up the C language spec, it states that in this context, the order of operations is as follows:
1. * operator
2. = (assignment) operator
3. ++ operator
So the while loop then becomes, in english:
while (some condition):
Take what is at address "t" and copy it over to location at address "s".
Increment "s" by one address location.
Increment "t" by one address location.
Now, what is "some condition"? The C lang specification also says that the value of an assignment expression is the assigned value itself, which in this case is *t.
So "some condition" is "t points to something that is non-zero", or in a simpler way, "while the data at location t is not NULL".
The C Programming Language (K&R) by Brian W. Kernighan and Dennis M. Ritchie gives a detailed explanation of this.
Second Edition, Page 104:
5.5 Character Pointers and Functions
A string constant, written as
"I am a string"
is an array of characters. In the internal representation, the array is terminated with the null character '\0' so that programs can find the end. The length in storage is thus one more than the number of characters between the double quotes.
Perhaps the most common occurrence of string constants is as arguments to functions, as in
printf("hello, world\n");
Where a character string like this appears in a program, access to it is through a character pointer; printf receives a pointer to the beginning of the character array. That is, a string constant is accessed by a pointer to its first element.
String constants need not be functions arguments. If pmessage is declared as
char *pmessage;
then the statement
pmessage = "now is the time";
assigns to pmessage a pointer to the character array. This is not a string copy; only pointers are involved. C does not provide any operators for processing an entire string of characters as a unit.
There is an important different between these definitions:
char amessage[] = "now is the time"; /* an array */
char *pmessage = "now is the time"; /* a pointer */
amessage is an array, just big enough to hold the sequence of characters and '\0' that initializes it. Individual characters within the array may be changed by amessage will always refer to the same storage. On the other hand, pmessage is a pointer, initialized to point to a string constant; the pointer may subsequently be modified to point elsewhere, but the result is undefined if you try to modify the string contents.
+---+ +--------------------+
pmessage: | o-------->| now is the time \0 |
+---+ +--------------------+
+--------------------+
amessage: | now is the time \0 |
+--------------------+
We will illustrate more aspects of pointers and arrays by studying versions of two useful functions adapted from the standard library. The first function is strcpy(s,t), which copies the string t to the string s. It would be nice just to say s = t but this copies the pointer, not the characters.To copy the characters, we need a loop. The array version is first:
/* strcpy: copy t to s; array subscript version */
void strcpy(char *s, char *t)
{
int i;
i = 0;
while((s[i] = t[i]) != '\0')
i ++;
}
For contrast, here is a version of strcpy with pointers:
/* strcpy: copy t to s; pointer version 1 */
void strcpy(char *s, char *t)
{
while((*s = *t) != '\0')
{
s ++;
t ++;
}
}
Because arguments are passed by value, strcpy can use the parameters s and t in any way it pleases. Here they are conveniently initialized pointers, which are marched along the arrays a character at a time, until the '\0' that terminates t has been copied to s.
In practice, strcpy would not be written as we showed it above. Experienced C programmers would prefer
/* strcpy: copy t to s; pointer version 2 */
void strcpy(char *s, char *t)
{
while((*s++ = *t++) != '\0')
;
}
This moves the increment of s and t into the test part of the loop. The value of *t++ is the character that t pointed to before t was incremented; the postfix ++ doesn't change t until after this character has been fetched. In the same way, the character is stored into the old s position before s is incremented. This character is also the value that is compared against '\0' to control the loop. The net effect is that characters are copied from t to s, up to and including the terminating '\0'.
As the final abbreviation, observe that a comparison against '\0' is redundant, since the question is merely whether the expression is zero. So the function would likely be written as
/* strcpy: cope t to s; pointer version 3 */
void strcpy(char *s, char *t)
{
while(*s++ = *t++);
}
Although this may seem cryptic as first sight, the notational convenience is considerable, and the idiom should be mastered, because you will see if frequently in C programs.
The strcpy in the standard library (<string.h>) returns the target string as its function value.
This is the end of the relevant parts of this section.
PS: If you enjoyed reading this, consider buying a copy of K&R - it is not expensive.
It works by copying characters from the string pointed to by 't' into the string pointed to by 's'. For each character copies, both pointers are incremented. The loop terminates when it finds a NUL character (equal to zero, hence the exit).
HINTS:
What does the operator '=' do?
What is the value of the expression "a = b"? Eg: if you do "c = a = b" what value does c get?
What terminates a C string? Does it evaluate true or false?
In "*s++", which operator has higher precedence?
ADVICE:
Use strncpy() instead.
it copies a string because arrays are always passed by reference, and string is just a char array. Basically what is happening is (if i remember the term correctly) pointer arithmetic. Here's a bit more information from wikipedia on c arrays.
You are storing the value that was dereferenced from t in s and then moving to the next index via the ++.
Say you have something like this:
char *someString = "Hello, World!";
someString points to the first character in the string - in this case 'H'.
Now, if you increment the pointer by one:
someString++
someString will now point to 'e'.
while ( *someString++ );
will loop until whatever someString points at becomes NULL, which is what signals the end of a string ("NULL Terminated").
And the code:
while (*s++ = *t++);
is equal to:
while ( *t != NULL ) { // While whatever t points to isn't NULL
*s = *t; // copy whatever t points to into s
s++;
t++;
}
Yes, it does have to do with pointers.
The way to read the code is this: "the value that is pointed to by the pointer "s" (which gets incremented after this operation) gets the value which is pointed to by the pointer "t" (which gets incremented after this operation; the entire value of this operation evaluates to the value of the character copied; iterate across this operation until that value equals zero". Since the value of the string null terminator is the character value of zero ('/0'), the loop will iterate until a string is copied from the location pointed to by t to the location pointed to by s.
Many adherents of ะก language are convinced that the "while (* s ++ = * t ++)"
is a genuine grace.
In the conditional expression of the loop "while",three side effects are inserted(shift of one pointer, shift of the second pointer, assignment).
The body of the loop as a result was empty, since all the functionality is placed in a conditional expression.
use for with int i:
char t[]="I am a programmer",s[20];
for(int i=0;*(t+i)!='\0';i++)
*(s+i)=*(t+i);
*(s+i)=*(t+i); //the last char in t '\0'
printf("t is:%s\n",t);
printf("s is:%s\n",s);
use for with pointer++:
char t[]="I am a programmer",s[20];
char *p1,*p2;
p1=t,p2=s;
for(;*p1!='\0';p1++,p2++)
*p2 = *p1;
*p2 = *p1;
printf("t is:%s\n",t);
printf("s is:%s\n",s);
use while with pointer++:
char t[]="I am a programmer",s[20];
char *p1,*p2;
p1=t,p2=s;
while(*p2++=*p1++);
printf("t is:%s\n",t);
printf("s is:%s\n",s);
printf("t is:%s\n",p1-18);
printf("s is:%s\n",p2-18);
use array to initialize pointers:
char a[20],*t="I am a programmer",*s;
s=a;
while(*s++=*t++);
printf("t is:%s\n",t-18);
printf("s is:%s\n",s-18);
printf("s is:%s\n",a);
starts a while loop....
*s = *t goes first, this assigns to what t points at to what s points at. ie, it copies a character from t string to s string.
what is being assigned is passed to the while condition... any non zero is "true" so it will continue, and 0 is false, it will stop.... and it just happens the end of a string is also zero.
s++ and t++ they increment the pointers
and it all starts again
so it keeps assigning looping, moving the pointers, until it hits a 0, which is the end of the string
Yes this uses pointers, and also does all the work while evaluating the while condition. C allows conditional expressions to have side-effects.
The "*" operator derefereces pointers s and t.
The increment operator ("++") increments pointers s and t after the assignment.
The loop terminates on condition of a null character, which evaluates as false in C.
One additional comment.... this is not safe code, as it does nothing to ensure s has enough memory allocated.
The question I provided the following answer on was closed as a duplicate of this question, so I am copying the relevant part of the answer here.
The actual semantic explanation of the while loop would be something like:
for (;;) {
char *olds = s; // original s in olds
char *oldt = t; // original t in oldt
char c = *oldt; // original *t in c
s += 1; // complete post increment of s
t += 1; // complete post increment of t
*olds = c; // copy character c into *olds
if (c) continue; // continue if c is not 0
break; // otherwise loop ends
}
The order that s and t are saved, and the order that s and t are incremented may be interchanged. The save of *oldt to c can occur any time after oldt is saved and before c is used. The assignment of c to *olds can occur any time after c and olds are saved. On the back of my envelop, this works out to at least 40 different interpretations.
Well this is true just in the case of the char if there is no \0 and the it is an integer array the the program will crash because there will be a address whose elements are not the part of the array or pointer, if the system has memory that was allocated using the malloc then the system will keep giving the memory