Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print a string using putch with pointers in C

Tags:

c

So I'm trying to print an inputted string using putch and a little bit of pointers.

Here is my current code:

#include<stdio.h>
#include<conio.h>
#include<string.h>

void printer(char *c);
char *c;
char ch;
main(){
  clrscr();
  printf("Enter a string: ");
  scanf("%s",&ch);
  c = &ch;
  printer(c);
  getch();
}


void printer(char *c){
  int x;
  for(x=0;x<strlen(c);x++){
     putch(*c);
  }
}

The problem is that i can only print the first character of the string, also for some reason strlen always return 3 for strings that are 3 characters and below.

Do I have to use array for this so that I can use putch since it is limited to only 1 character output.

like image 239
magicianiam Avatar asked Oct 21 '22 05:10

magicianiam


2 Answers

One of the problems is that your printer() function is not printing anything other than the first character. There are two ways of approaching this. Using pointers:

void printer(char const *c){
    while ( *c != '\0' ) {
        putch(*c);
        c++;
    }
}

And using pointer arithmetic:

void printer(char const *c) {
    int x;
    for ( x=0; x < strlen(c); x++ ) {
        putch( *(c + x) );
    }
}

The biggest problem is that you are attempting to store a string in a single character in memory. That's just asking for problems.

char ch;
scanf("%s",&ch); // NO NO NO NO NO

Instead declare your buffer (to store the string in) as an array big enough for the biggest string you expect:

char ch[512];
scanf("%s", ch);
like image 137
PP. Avatar answered Nov 03 '22 06:11

PP.


First off, you pass a pointer to "storage for one character" to scanf. Anything that happens after that is in nsal demons territory.

Second, scanf does not allocate storage for your input, so even if you'd passed c instead of &ch, you would not be any better off.

Third, you really should be declaring your variables inside main rather than using global variables.

Something like this may be closer to what you actually want:

void output (char *c)
{
   char *cp;
   for (cp = c; *cp; cp++) {
     putch(*cp);
   }
}

int main (void)
{
  char input[80];
  printf("Please input a string: ");
  scanf("%s\n", input);
  output(input);
}
like image 34
Vatine Avatar answered Nov 03 '22 05:11

Vatine