gpt4 book ai didi

c++ - 你能改变指针指向的大小吗

转载 作者:太空宇宙 更新时间:2023-11-04 16:27:53 25 4
gpt4 key购买 nike

例如,如果一个指针指向一个字符数组,上面写着“你好,你好吗?”而你只希望指针指向 Hello。我传入一个 char 指针,当我计算它时,它会读取整个数组。我尝试使用 for 循环来减小大小,该循环在遇到 ' ' 时会中断。但我没有运气弄清楚。有任何想法吗?

const char *infile(char * file )
{
cout<<file<<endl; //this prints out the entire array
int j;
for(j=0;j<500; j++)
{
if(file[j]==' ')
break;
}
strncpy(file, file, j);
cout<<file<<endl; //how to get this to print out only the first word
}

最佳答案

如果源字符串的前 j 字节中没有空终止符,则

strncpy() 不会附加空终止符。而你的情况,没有。

我认为你想要做的是手动将第一个空格更改为 \0:

for (j = 0; j < 500; j++) {
if (file[j] == ' ') {
file[j] = '\0';
break;
}
}

关于c++ - 你能改变指针指向的大小吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10180425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com