-1

I am trying to append a string t in a string s using pointers.

#include<stdio.h>
#include "my_functions.h"
int main(void)
   {
     char* s = "H"; /*First string*/
     char* t = "W"; /*String to be appended*/
     char* buff;    /*used to store the initial value of s pointer*/
     buff = s;
     while(*s != '\0')
     {
       s++;
     }


     /*At the end of the loop I will get a memory add where string s 
       ends*/

     /*Start appending second string at that place*/ 


     char* temp;    /*Creating a temporary pointer to store content 
                      value of second string*/
     temp = t;

     t = s;     /*t now points to the new starting position for 
                    appending operation*/

     *t = *temp;   /*------ERROR-------*/

     /*Rest is to just print the whole appended string at 
                 once*/
     s = buff;
     while(*s!='\0')
     {
       printf("%c\t",*s);
       s++; 
     }


     printf("Works Fine");
     return 0;
   }

I am not getting any output on the terminal, nor any errors. The Idea is to change the content of new location of t which is '\0' to the content of t to be appended that is 'W'. I am a noob. Any suggestions? Where Am I wrong?

smartnerd
  • 85
  • 6
  • 3
    You can't modify string literals — often, you'll crash, but the behaviour is undefined so anything can happen. You've not allocated enough space to copy the string into the new space. Use `char s[20] = "H";` — now you can append to the string safely. – Jonathan Leffler Jun 01 '17 at 09:45
  • @JonathanLeffler Ok I tried that. I increased a digit in first string and stopped the while loop for position at second last character i.e before '\0'. Now second string must get appended as it has 2 places empty. But still no result. – smartnerd Jun 01 '17 at 09:51
  • The loop `buff = s; while(*s != '\0') { s++; }` is surprising. Shouldn't you be modifying `buff`, not `s`? Certainly, if you use `char s[20] = "H";`, you can't increment `s` any more. Are you ignoring any compiler warnings? If so, don't. Repent thy evil ways! Compiler warnings are telling you about bugs — they will tell you about bugs every time until you don't need to ask questions on SO about what to do, and beyond that. (When I get compiler warnings, they still mean bugs in my code — I fix them before I run the code.) – Jonathan Leffler Jun 01 '17 at 09:54
  • 1
    I've not looked through the whole code. It looks like it is working very hard to do something that should be very succinct. Given `char s[20] = "H";`, you might write: `char *dst = s; while (*dst != '\0') dst++; char *src = t; while ((*dst++ = *src++) != '\0') ; printf("s [%s]\n", s);`. You can add other print statements as you see fit. Note the square brackets around the string; those help identify the end of the string, and show up problems like unexpected carriage returns (not likely to be a problem here, but in other contexts…). – Jonathan Leffler Jun 01 '17 at 09:58
  • @JonathanLeffler Thanks :) – smartnerd Jun 01 '17 at 10:02
  • @JonathanLeffler I did take your advice, posted my comment before reading your third comment. That is why Thanks. Thanks for the solution. :)) – smartnerd Jun 01 '17 at 10:06
  • "I did not convert s into an array that is why I am still able to increment s" - 1) A pointer is not an array anyway. 2) Both partss of this sentence are completely unrelated there is no such implication `pointer => can be incremented`. 3) Please do youself a good and us a favour and get the basics right. If your teacher can't, a good C book might. If none helps: Knitting is also a fine trade. – too honest for this site Jun 01 '17 at 10:10
  • @Olaf, totally agreed, It doesn't make any sense. I was maybe replying to the other comment of Jonathan "`while(*s != '\0') {s++;}` is surprising" and wrote a mess. What I meant was s++ is there due to pointer or else I could have used `s[i], i++;` . And thanks for the third remark, "if none helps: Knitting is also a fine trade".I might be a noob today but this will definitely teach me what not to become when you know things and have an option to help people or to be cocky. Kudos.!! – smartnerd Jun 01 '17 at 10:32
  • @smartnerd: The index-operator `[]` **only** works on … pointers! So that's one more statement of yours which shows missconception (just don't understand me puitting a finger at it as offence). You really need to read a book! As a last word: **Don't try learning C from youtube videos or online tutorials! It is a guarantee to faill**. – too honest for this site Jun 01 '17 at 10:39
  • 1
    Try to understand this code ... : `char *strcat(char *dest, const char *src) { char *ret = dest; while (*dest) dest++; while (*dest++ = *src++) ; return ret; } ` – Sir Jo Black Jun 01 '17 at 10:42
  • @Olaf, Thanks for pointing that out. I did not know that. I am trying to comprehend The C programming language By Dennis and Brian W. Its a bit overwhelming but I hope I will do some practise and will get a good grip in year or so. – smartnerd Jun 01 '17 at 10:44
  • @SergioFormiggini works like charm. But In my code I am unable to understand one thing, why `*temp = *t` is crashing.. See like in your code..`*dest++ = *src++` works fine, that is what I was trying to do. – smartnerd Jun 01 '17 at 10:47
  • 2
    Whlie The K&R book **2nd rev(!)** is fine to get the basics, it is outdated wrt the C language since ca. 18 years. C has evolved with C99 quite a bit, some changes are not compatible. So you should get a book about modern C, if possible standard C which is C11 **only** or at least C99 and learn about the changes/additions (mostly the latter) C11 provides. – too honest for this site Jun 01 '17 at 10:51
  • @Olaf, Roger that.!! – smartnerd Jun 01 '17 at 11:01
  • 1
    @smartnerd. Keep in your mind that "W" and "H" are constants! `t`, `s` and `temp` points them and them are in a constants memory area, then a segmentation fault is issued! – Sir Jo Black Jun 01 '17 at 11:14
  • Possible duplicate of [How do I concatenate const/literal strings in C?](https://stackoverflow.com/questions/308695/how-do-i-concatenate-const-literal-strings-in-c) – Persixty Jun 01 '17 at 11:16

1 Answers1

2

I suggest you to study this code:

char *strcat(char *dest, const char *src)
{
   char *ret = dest;

   while (*dest)
      dest++;

   while (*dest++ = *src++)
    ;

    return ret;
 }

Obviously the input parameter dest MUST be a pointer that points a memory area at least big as the sum of the two strings length (pointed by dest and src) + 1 byte (the 0 terminator).

Sir Jo Black
  • 2,024
  • 2
  • 15
  • 22