0

This is a very small question, and probably something really silly! But why am I getting garbage returned in my output for this function which should remove double letters?

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

char  *makehello( char *s ) {
   char new[16] ;
   int i ;
   int c = strlen(s);
   for ( i = 0; i < (c + 1); i++)
     if (toupper(s[i]) != toupper(s[i+1]))
       new[i] = toupper(s[i]);
return strdup( new ) ;  
}

int main(void) {
 char *new;
 char data[100];
 scanf("%s", data);
 new = makehello(data);
 printf("%s", new);
return 0;
}
5
  • What happens when there are more than 16 result letters? Commented Nov 24, 2011 at 16:50
  • Im just playing atm with aabb aacc etc to test it, but getting garbage printed :/ Commented Nov 24, 2011 at 16:51
  • Make sure you terminate the result. Initialise it as char new[16] = { 0 };. Commented Nov 24, 2011 at 16:53
  • Still not making a difference Commented Nov 24, 2011 at 16:54
  • Im not getting any compiler warnings, just getting garbage printed. Not sure why at all though. Commented Nov 24, 2011 at 17:03

3 Answers 3

2

You need a separate count for your 'new' array. You're storing them at index 'i' (where you found the character), but what you really want is to store them from position 0 and increment this count instead.

EDIT: Of course this isn't a fullproof method.

i.e something like this:

   for ( i = 0; i < c; i++)
   {
        if (toupper(s[i]) != toupper(s[i+1]))
        {
            new[count++]= toupper(s[i]);
        }
   }
   new[count] = '\0';
Sign up to request clarification or add additional context in comments.

Comments

0

The line

for ( i = 0; i < (c + 1); i++) 

should be

for ( i = 0; i < (c - 1); i++)

And you then need before the strdup new[i]=0;

Braces would not go amise either.

EDIT

Forgot need to change the following

int i, j=0;

and in the for loop

new[j++] = toupper(s[i]);

and after the for loop

new[j] = 0;

2 Comments

Im still getting garbage output :/
i.e. bbb returns just garbage output
0

Here's a reasonably compact C99 version of the algorithm (headers omitted, example):

const char * makehello (const char * s)
{
  char new[16] = { *s, 0 };
  const char * p = s;
  char c = *s, * q = new;

  while (*p) { if (*++p != c) { c = *++q = *p; } }

  return strdup(new) ;
}

int main(void)
 {
  char data[100];
  scanf("%s", data);
  printf("%s", makehello(data));
  return 0;
}

(This one discriminates case.)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.