C: Doubling each letter in a String

Viewed 366

I am studying C as of now and I am stuck on this question.

Input: 'abc'
Output: 'aabbcc'

I am stuck with the pointers and increasing the size buffer. See below

Edit: added the main()

#include <stdio.h>
#include <string.h>
int main()
{
   char destValue[];
   char srcValue[];    

   //User input
   printf("Please enter valid text: " );
   scanf("%s", srcValue);

   //Copying to memory
   memcpy(destValue, srcValue, strlen(srcValue)+1);
   char lenghtOfText = strlen(srcValue); 

   for(int i = 0; i < lenghtOfText; i++) {
      tempValue[i] = strcat(tempValue, srcValue);
   }
}

Every time I am running my code, it keeps on failing and the error message is Abort 6. Upon searching, they said the tempValue does not increase the size of the buffer.

Sorry, if my code isn't working and I am just learning C programming. Thanks for understanding

3 Answers

Simply You can do like this

   #include<stdio.h>
#include<malloc.h>
#define len 10
int main()
{
        char *destValue;
        char *srcValue;

        srcValue = malloc(len * sizeof(char));
        destValue = malloc((2 * len * sizeof(char)) + 1);
        //User input
        printf("Please enter valid text: " );
        scanf("%s", srcValue);
        int j = 0;
        for(int i = 0  ;srcValue[i]!= '\0';i++) {
                destValue[j++]= srcValue[i];
                destValue[j++]= srcValue[i];
        }

        destValue[j]='\0';
        puts(destValue);

        free(destValue);
        free(srcValue);

        return 0;
}

I hope you will get this.

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


int main(int argc, char const *argv[]) {
  char* srcValue = "Hello World";
  char* output = calloc(strlen(srcValue)*2+1, sizeof(char));
  for (int i=0; i<strlen(srcValue); i++){
    output[2*i] = srcValue[i];
    output[2*i+1] = srcValue[i];
  }
  output[2*strlen(srcValue)] = '\0';
  printf("%s\n", output);
  return 0;
}

destValue and srcValue are essentially pointers to char arrays. But you did not allocate any memory to them. The scanf function will attempt to copy the entered text into an initialized memory location.

Related