Friday, July 31, 2009

C-programming l as a beginner i need help here. this is the question:?

Write a C program tha t p rint s the character s in a s t ring in rever se order.


char s[10] = "abcdefg";


char* cptr;


i can do without the pointers. which is simple but i need someone to use pointers!!!

C-programming l as a beginner i need help here. this is the question:?
try this:


#include "stdio.h"


#include "stdlib.h"


int main(){


printf("type a string:\n");


char* s = malloc(1);


int c = 0;


*s = getchar();


while(s[c] != '\n'){


c++;


s = realloc(s,c + 1);


s[c] = getchar();


}/*this gives a string, terminated by a newline*/


while(c != -1){


putchar(s[c]);


c--;


}


free(s);


}


but srsly, don't expect me or my fellow professionals to help you all the time!
Reply:Do you understand what the pointer is? My guess is that you are a little confused about that.





You probably have already learned that C does not have a variable to type string. One way to build a string is to use an array. In C, an array is a group of memory addresses that are next to each other (what is important is that the addresses are next to each other). Now, you don't know which memory addresses in your computer store this array. If you knew, you could go to the end of the array and print the value in the address. You would repeat this for the previous address, and so on until you got to the first address.





Like I said, YOU don't know where the array is stored, but your computer does. Use a pointer to look at (point to) the first element of the array. By incrementing the pointer, you look at the next memory address. So if you can find the end of the string (\0), you can decrement the pointer to look at the previous memory address.





Hope this makes sens.
Reply:Keep asking people to do your homework for you and you'll always fail in programming :P
Reply:Have you tried _anything_ yet?





int i = strlen(s);


char *cptr = %26amp;s[i - 1];





printf ("fwd: %s\n", s);


printf ("rev: ");


while(cptr %26gt;= s) {


printf("%c", *cptr--);


}


printf("\n");

survey questions

No comments:

Post a Comment