鉴于以下计划,
#include <iostream>
using namespace std;
void foo( char a[100] )
{
cout << "foo() " << sizeof( a ) << endl;
}
int main()
{
char bar[100] = { 0 };
cout << "main() " << sizeof( bar ) << endl;
foo( bar );
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出
main() 100
foo() 4
Run Code Online (Sandbox Code Playgroud)
在这个声明中:
char *a = "string1"
Run Code Online (Sandbox Code Playgroud)
究竟什么是字符串文字?是string1吗?因为这个线程C和C++中字符串文字的类型是什么?说些不同的东西.
据我所知
int main()
{
char *a = "string1"; //is a string- literals allocated memory in read-only section.
char b[] = "string2"; //is a array char where memory will be allocated in stack.
a[0] = 'X'; //Not allowed. It is an undefined Behaviour. For me, it Seg Faults.
b[0] = 'Y'; //Valid.
return 0;
}
Run Code Online (Sandbox Code Playgroud)
请添加除上述要点之外的一些细节.谢谢.
调试输出显示错误 a[0] = 'Y';
Reading symbols from /home/jay/Desktop/MI/chararr/a.out...done.
(gdb) b main
Breakpoint 1 at 0x40056c: …Run Code Online (Sandbox Code Playgroud) 我试图理解指针,这是我正在尝试实施的K&R程序.该程序是strcpy与KR的代码.
/*strcpy: copy t to s; pointer version 3*/
void strcpy(char *s, char *t){
while(*s++ = *t++)
;
}
Run Code Online (Sandbox Code Playgroud)
所以为了实现这个程序,我补充道
#include<stdio.h>
int main(){
char *s="abc", *t="ABC" ;
strcpy(s,t);
printf("%s\n",t);
printf("%s\n", s);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是,当我运行它时,我收到分段错误.我确信我错过了一些东西,但不太确定是什么.
谢谢!