我尝试用char指针复制字符串,程序没有给我什么,我也不知道......
请告诉我代码的问题。
int main() {
char *a = "helloworld.txt";
char *b = malloc( sizeof(char) * 20 );
while(*a!='\0') {
*b++=*a++;
}
*b = '.';
b++;
*b = '\0';
printf("string: %s\n", b);
}
结果是:
string:
答案 0 :(得分:6)
你需要这个:
int main() {
char *a = "helloworld.txt";
char *b = malloc( sizeof(char) * 20 );
char *c = b; // save pointer to allocated memory
while(*a!='\0') {
*b++=*a++;
}
*b = '.';
b++;
*b = '\0'; // b points to the end of the constructed
// string now
printf("string: %s\n", c); // use pointer saved before instead of b
}
答案 1 :(得分:1)
这是因为当您说printf("string: %s\n", b);
时,您试图从b
但*b = '\0'
开始打印字符串。所以难怪空字符串。
将指针b
保存到temp
指针,我们将用它来打印字符串,因为指针b
在while
循环中不断增加我们松开了弦乐的开始。或者
在评论中使用@Barmar建议的printf("string: %s\n", (b - (strlen(a)+1));
。
另外,b
之后,您如何确定malloc
指向有效的内存位置?此代码容易出错,可能会导致SegFault
。
通过将指针与malloc, calloc etc.
NULL
后是否已分配内存
char *b = malloc( sizeof(char) * 20 );
if(!b)
{
printf("Memory not allocated!\n");
exit(1);
}
答案 2 :(得分:0)
最初的问题是您修改了指向目标字符串的指针。 echo 'export PATH=$HOME/local/bin:$PATH' >> ~/.bashrc
. ~/.bashrc
mkdir ~/local
mkdir ~/node-latest-install
cd ~/node-latest-install
curl http://nodejs.org/dist/node-latest.tar.gz | tar xz --strip-components=1
./configure --prefix=~/local
make install # ok, fine, this step probably takes more than 30 seconds...
curl https://www.npmjs.org/install.sh | sh
指向字符串终止符,因此以下b
只会看到一个空字符串。使用临时指针递增。
但是,增量还有其他 - 更严重(就程序稳定性而言)问题:您更改指向已分配对象的唯一指针。因此,你不能再printf
了。
一般来说,一旦你不再需要它,你应该free
分配一个内存块。
始终检查功能报告的错误。 free
可能会失败,返回空指针。取消引用空指针是未定义的行为。你不想遇到它!
答案 3 :(得分:0)
void main(){
char *str1;
printf("\nEnter the string to be copied\n");
scanf("%[^\n]s",&*str1);
copystr(&str1);
getch();
clrscr();
}
copystr(char **str1){
char **str2;
int i=0;
while(**str1!='\0'){
// printf("address if str1 %u ",*str1);
*str2=*str1;
printf("\n%c",**str2);
(*str1)++;
(*str2)++;
i++;
printf(" address of str2 %u ",*str2);
}
*str2=(*str2)-i;
// printf("%d",i);
printf("\n%s",*str2);
}