修改字符串文字 [英] Modifying String Literal
问题描述
为什么没有输出,当我运行此程序。
#包括LT&;&stdio.h中GT;诠释的main()
{
字符* T =C ++;
T [1] ='P';
T [2] ='P';
的printf(%S,T);
返回0;
}
有其他的几个问题你code。
-
指针通常用来指向一个已经存在的数据,所以你可以使用它像这样
改编的char [] =C ++;
的char * T =&放大器;常用3 [0];
另外修改,
T [1] ='P';T [2] ='P';
当然有使用字符串的一种特殊的方式 - 让指针指向一个字符串常量。只是你使用的方式:
的char * T =C ++; //你不能修改它在大多数操作系统
T [1] ='P';
T [2] ='P';
有是使用它的一个更好的方法,这是更轻便和易于理解的:
为const char * T =C ++;
2.You code有很多的地方,是不是在C标准
的#include<&stdio.h中GT; //你最好加之间的空间,这是一个很好的编码约定
#包括LT&;&CONIO.H GT; //只支持VC / VS在Windows中,你可以使用的getchar()代替INT的main()//主返回int
{
字符* T =C ++; T [1] ='P';
T [2] ='P';
的printf(%S \\ n,T); //这是一个好习惯,打印字符串时,添加的'\\ n'
的getchar(); //的getchar()是由C标准库支持 返回0; //此处返回0
}
3。关于打印字符串
Linux是行缓冲(如果你使用的是Windows忽略这个:P)及更容易在控制台读取,你最好在你打印的字符串末尾添加的'\\ n':
的printf(%S \\ n,T);
如果你不希望有一个字符串后回车。在窗户只使用你喜欢的:
的printf(%S,T);
在Linux中,你应该在stdlib.h中添加fflush()。
的printf(%S,T);
fflush(标准输出);
Why is there no output when i run this program.
#include<stdio.h>
int main()
{
char* t="C++";
t[1]='p';
t[2]='p';
printf("%s",t);
return 0;
}
There are several other problems with your code.
Pointers are usually used to point to data that already exists, so you can use it like this
char arr[] = "C++";
char* t = &arr[0];
Also modifiable,
t[1] = 'p';
t[2] = 'p';
of course there is a special way of using string —— let the pointer point to a string constant. Just the way you used:
char *t = "C++"; // you cannot modify it in most operating systems
t[1] = 'p';
t[2] = 'p';
There is a better way of using it, which is more portable and easy to understand:
const char* t="C++";
2.You code have many place that is not in c standard
#include <stdio.h> // You'd better add a space between, for this is a good coding convention
#include <conio.h> // only supported by vc/vs in windows, you can use getchar() instead
int main() // main returns int
{
char* t = "C++";
t[1] = 'p';
t[2] = 'p';
printf("%s\n", t); // it's a good habit to add a '\n' when printing a string
getchar(); // getchar() is supported by c standard library
return 0; // return 0 here
}
3.about printing string
Linux is line-buffered(ignore this if you are using windows :P) & for easier to read in console, you'd better add a '\n' at the end of you printed string:
printf("%s\n",t);
If you don't want to have a carriage return after a string. In windows use just as you like:
printf("%s",t);
In Linux, you should add a fflush() in stdlib.h.
printf("%s",t);
fflush(stdout);
这篇关于修改字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!