I am very new in C programming and have a question about it. I have the code bel
ID: 662950 • Letter: I
Question
I am very new in C programming and have a question about it. I have the code below and I need to rewrite it by dereferencing ptr (or some modification of ptr), NOT array indexing. I am asked for a solution with pointer arithmetic in the loop. Can anyone help please?
#include<stdio.h>
main () {
int i=0, len;
char s[ ] = "First Code!";
len = strlen(s);
for( i=0; i<len; i++)
putc(s[i], stdout);
printf(" length = %d ", i);
}
I did the following code but my teacher said that this is not what I am supposed to do when dereferencing a pointer (however this code is correct)
#include<stdio.h>
#include <string.h>
main () {
int i=0, len;
char s[ ] = "First Code!";
char *ptr;
ptr = s;
len = strlen(ptr);
for(i = 0; i < len; i++)
putc(ptr[i], stdout);
printf(" length = %d ", i);}
Any help is appreciated.
Explanation / Answer
Dereferencing of pointers is be done with the help of dereference operator which is an unary operator denoted by, " * ". The operator when used with a pointer variable returns the l-value which is equivalent to the value at the pointer address. For e.g. Consider a pointer x as below:
char* x = "Hello"
Six bytes with the numerical values used to encode the letters 'H', 'e', 'l', 'l' , 'o' and a 0 byte to denote the end of the textual data, are stored somewhere in memory and the numerical address of that data is stored in x.
*x denotes the value 'H', similarly x[1] or *(x+1) denotes the value 'e' and so on.
So, we can write the above program simply as :
#include<stdio.h>
main () {
char* ptr ="First Code!";
while (*ptr!='')
{
putc(*ptr++, stdout);
}
}
Or we can also take the string into an array and put it's value in the pointer and then dereference it to print the String.
#include<stdio.h>
main () {
char s[ ] = "First Code!";
char* ptr;
ptr=s;
while (*ptr!='')
{
putc(*ptr++, stdout);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.