如何使用指针更改字符串的第一个字符? [英] How do I change the first character of string using pointers?

查看:163
本文介绍了如何使用指针更改字符串的第一个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

int main() {
	char *string = "Programming is EPIC!";
	*string = 'K';

	printf("%s\n", string);

	_getch();
	return EXIT_SUCCESS;
}





此代码无法编译并出错!我在一本书中读到了这个例子,它说它应该编译但编译器会出错!



注意:如果在Linux上编译,请删除< conio。 h取代;和_getch(); function。



This code does not compile and gives errors! I read this example in a book and it says that it should compile but the compiler gives errors!

NOTE: If compiling on Linux, please remove the <conio.h> and _getch(); function.

推荐答案

最好为字符串提供一些内存而不是填充它。



It is better to provide some memory to the string and than fill it.

char string[30];
strcpy(string,"Programming is EPIC!");
string[0] = 'K';





你最好注意一些字符串库来照顾这样的烦人任务。 ;-)

所以这样的代码可以完成这项工作



You better look out for some string library to take care about such annoying tasks. ;-)
So such code would do the job

std_string string = "Programming is EPIC!";
string[0] = 'K';


问题是你的字符串是一个常量:所以当你试图以任何方式改变它时,你会得到一个访问违规例外,你的程序会崩溃。



你需要做的是手动将它复制到一个数组中:

The problem is that your string is a constant: so when you try to alter it in any way, you will get an "Access violation" exception and your program will crash.

What you need to do is make a copy of it into an array, either manually:
char* inp = "Programming is EPIC!";
char string[100];
int i;

for (i= 0; i < 100; i++)
    {
    string[i] = inp[i];
    if (string[i] == '\0') break;
    }
*string = 'K';

或自动:

Or automatically:

char string[] = "Programming is EPIC!";
*string = 'K';


这篇关于如何使用指针更改字符串的第一个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆