[英]How do you assign substrings in C?
I'm trying to figure out why this doesn't work: 我试图找出为什么这不起作用:
#include <stdio.h>
int main ()
{
char *orig = "Hey you guys.";
char *str;
str = &orig;
while(*str++) {
if (*str == 'y')
*str = '@';
}
puts(orig);
return 0;
}
// OUTPUT => "Hey you guys."
// Not "he@ @ou gu@s." as expected.
By assigning str = &orig, I thought that str would share the same memory address as orig. 通过分配str =&orig,我认为str将与orig共享相同的内存地址。 What am I missing? 我想念什么?
Two things: 两件事情:
&orig
is the address of the pointer . &orig
是指针的地址 。 Perhaps you want str = orig
. 也许您想要str = orig
。 Your compiler should have warned you about a pointer type mismatch here; 您的编译器应该在此处警告您有关指针类型不匹配的信息。 if it didn't, then turn up the warning level until it does. 如果不是,则提高警告级别,直到达到警告级别为止。 char orig[] = "Hey you guys."
使用char orig[] = "Hey you guys."
, which copies the literal string into an array called orig
that you can safely modify. ,它将文字字符串复制到可以安全修改的名为orig
的数组中。 (1) for sharing memory you want to do str = orig
, since str
is already a pointer type. (1)为了共享内存,您想做str = orig
,因为str
已经是一个指针类型。
(2) orig
is defined as a string literal, a constant - so you cannot modify the value "Hey you guys."
(2) orig
被定义为字符串文字, 一个常量 -因此您无法修改值"Hey you guys."
, even not when accessing it via str
, it will result in a run time error. ,即使没有通过str
访问它,也会导致运行时错误。
EDIT: Issue #3: In your while loop, you first increase the pointer, and only then checks if it is 'y' and modify. 编辑:问题3:在while循环中,您首先增加指针,然后才检查它是否为“ y”并进行修改。 By doing so - you will miss the first element . 这样, 您将错过第一个元素 。 "yasdf"
will become "yasdf"
and not "@asdf"
, as you expect. 如您所料, "yasdf"
将变为"yasdf"
而不是"@asdf"
。 [well I think that what you expect anyway...] [好吧,我认为无论如何您期望...]
To achieve what you are after, you can follow this: [using strcpy and a buffer, to avoid writing on constant memory] 要实现您所追求的目标,可以按照以下步骤操作:[使用strcpy和一个缓冲区,以避免写入恒定内存]
#include <stdio.h>
#include <string.h>
int main ()
{
char *orig = "Hey you guys.";
char buff[14]; //the length of orig + 1 byte for '\0'
char *str = buff; //since str and buff are already pointers
strcpy(str,orig);
while(*str) {
if (*str == 'y')
*str = '@';
str++;
}
puts(buff);
return 0;
}
#include <stdio.h> int main () { char orig[] = "Hey you guys."; char *str; str = orig; int i; while(*str){ if (*str == 'y') *str = '@'; *str++; } puts(str); puts(orig); return 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.