In: Computer Science
q7.1 Fix the errors in the code (in C)
//This program should read a string from the user and print it using a character pointer
//The program is setup to use pointer offset notation to get each character of the string
#include <stdio.h>
#include <string.h>
int main(void){
char s[1];
scanf(" %c", s);
char *cPtr = s[1];
int i=0;
while(1){
printf("%c", cPtr+i);
i++;
}
printf("\n");
}
CODE IN C:-(With documentation and required correction)
#include <stdio.h>
#include <string.h>
int main(void){
char str[100]; //STRING CAN BE OF LENGTH MORE THAN 1 so we need to take length more than 1
scanf(" %s", str);
char *cPtr = str; //to store the address of first character in string just write character array name
while(*cPtr) //Here we cannot take 1 inside
while() because if we take 1 then it will always be true and run
for infinite times
{
printf("%c", *cPtr++); //to access the value of address we need to use * before it and also instead of using *cPtr+i each time //we can use *cPtr++
}
printf("\n");
}
SCREENSHOTS:-