如何在不改变指针地址的情况下改变指针的内容?
How to change the content of pointer without changing its pointing address?
我正在尝试使用指针将字符串 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 != '[=10=]')
{
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!='[=10=]')
{
printf("%c\t",*s);
s++;
}
printf("Works Fine");
return 0;
}
我在终端上没有得到任何输出,也没有得到任何错误。想法是将t
的新位置'\0'的内容更改为要附加的t
的内容'W'
。我是菜鸟。有什么建议么?我哪里错了?
我建议你学习这段代码:
char *strcat(char *dest, const char *src)
{
char *ret = dest;
while (*dest)
dest++;
while (*dest++ = *src++)
;
return ret;
}
显然输入参数dest
必须是一个指针,它指向的内存区域至少是两个字符串长度之和(由dest
和src
指向)+ 1 字节(0 终止符)。
我正在尝试使用指针将字符串 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 != '[=10=]')
{
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!='[=10=]')
{
printf("%c\t",*s);
s++;
}
printf("Works Fine");
return 0;
}
我在终端上没有得到任何输出,也没有得到任何错误。想法是将t
的新位置'\0'的内容更改为要附加的t
的内容'W'
。我是菜鸟。有什么建议么?我哪里错了?
我建议你学习这段代码:
char *strcat(char *dest, const char *src)
{
char *ret = dest;
while (*dest)
dest++;
while (*dest++ = *src++)
;
return ret;
}
显然输入参数dest
必须是一个指针,它指向的内存区域至少是两个字符串长度之和(由dest
和src
指向)+ 1 字节(0 终止符)。