为什么当我运行这个程序时没有输出。
#include<stdio.h>
int main()
{
char* t="C++";
t[1]='p';
t[2]='p';
printf("%s",t);
return 0;
}
发布于 2011-03-29 08:08:54
你的代码还有其他几个问题。
char arr[] = "C++";
char* t= &arr;
也可以修改,
t[1] = 'p';
t[2] = 'p';
当然,有一种特殊的字符串使用方式--让指针指向字符串常量。就像你使用的那样:
char *t = "C++"; // you cannot modify it in most operating systems
t[1] = 'p';
t[2] = 'p';
有一种更好的使用方法,它更易于移植和理解:
const char* t="C++";
2.你的代码有很多地方不在c标准中。
#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.关于打印字符串
Linux是行缓冲的(如果您使用的是windows :p,则忽略这一点)&为了在控制台中更容易阅读,您最好在打印字符串的末尾添加一个'\n‘:
printf("%s\n",t);
如果你不想在字符串后面有一个回车符。在windows中,您可以随意使用:
printf("%s",t);
在Linux中,您应该在stdlib.h中添加一个fflush()。
printf("%s",t);
fflush(stdout);
发布于 2011-03-29 03:42:02
"C++“是存储在只读位置中的字符串,因此无法修改。有了这个-
char* t="C++"; // t is pointing to a string literal stored in read only location
相反,你应该有-
char t[] = "C++" ; // Copying the string literal to array t
才能真正做到-
t[1] = 'p' ;
发布于 2011-03-29 03:45:39
标准运行时库的某些版本需要\n
才能显示输出。
printf("%s\n",t);
https://stackoverflow.com/questions/5464183
复制相似问题