如何在不改变指针地址的情况下改变指针的内容?

时间:2017-06-01 09:42:49

标签: c string pointers strcat

我正在尝试使用指针在字符串t中附加字符串s

#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;
   }

我没有在终端上获得任何输出,也没有任何错误。该提示是将t的新位置内容更改为t的内容'W',即int cast_to_double(char *str, double *result) { char *remaining_str; double number; number = strtod(str, &remaining_str); /* we want to get only a double as parameter */ if ( strlen(remaining_str) > 0 ) { return 0; } *result = number; return 1; } 。我是个菜鸟。有什么建议?我错在哪里?

1 个答案:

答案 0 :(得分:2)

我建议你研究这段代码:

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

   while (*dest)
      dest++;

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

    return ret;
 }

显然输入参数dest必须是一个指针,它将内存区域指向至少大两个字符串长度的总和(由destsrc指向)+ 1字节(0终结者)。