Here's a C program to find reverse of a string using pointers with output and explanation. This program uses C concepts like Pointers in C, Malloc function in C, Sizeof function in C and For Loop in C.
# include <iostream.h> int main(){ char *string = (char*) malloc(11*sizeof(char)), temp; int length; printf("Enter the no of letters in the string (max 10): "); scanf("%d", &length); for(int i = 0;i < length;i++){ printf("\nEnter character %d: ", (i + 1)); scanf("%c", &temp); *(string + i) = temp; } *(string + length + 1) = '\0'; printf("\nYou entered: %s", string); printf("\nReverse of your string: "); for(int i = length - 1;i >= 0;i--){ printf("%c", *(string + i)); } return 0; }
Output of above program
Enter the no of letters in the string (max 10): 6
Enter character 1: s
Enter character 2: t
Enter character 3: r
Enter character 4: i
Enter character 5: n
Enter character 6: g
You entered: string
Reverse of your string: gnirts
Explanation of above program
Malloc function used in this program is to dynamically allocate memory to pointer. Malloc needs size of memory that needs to be allocated as an argument. Malloc returns void pointer or void*.
(char*) malloc(11*sizeof(char))
By sizeof(char) we mean size of character which is usually 1 byte. The above line means that malloc needs to allocate 11*sizeof(char) or 11*1 bytes of memory on the stack.
As mentioned above that malloc returns void* that is why a type conversion to char* is needed as we want memory block for character data.
thanx alot...
but plz can u tell me how file concept is used in such programss..i can't understand file concepts..