简体   繁体   English

如何将char *转换为char []

[英]How to convert a char* to a char[]

I was wondering if there was a way to convert a string that has its first letter pointed at by a char* to a char[], so it is no longer a pointer, but a literal char[]. 我想知道是否存在一种方法,可以将第一个字母由char *指向的字符串转换为char [],因此它不再是指针,而是文字char []。

For example, if my string is "hi my name is bob\\0", and char* pointer had this string copied to it via memcpy, is there a way to turn this back to a char[]? 例如,如果我的字符串是“ hi,我的名字是bob \\ 0”,并且char* pointer通过memcpy复制了该字符串,是否可以将其转换回char []?

Any help would be appreciated. 任何帮助,将不胜感激。

there is no need to convert, You can index a pointer as if it was an array. 无需转换,您可以像建立数组一样索引一个指针。 you can just to 你可以

char * a;

ant then do 蚂蚁然后做

char ch = a[4];

here is a similar question here 这里有一个类似的问题在这里

ther other way is also as easy 其他方法也一样容易

void f(int* p);

int x[5];
f(x);     // this is the same as f(&x[0])

They are the same thing. 他们是一样的东西。 a[i] is equivalent to *(a + i), so much so that you can write i[a] and get the same result! a [i]等效于*(a + i),因此您可以写i [a]并获得相同的结果!

something like this? 这样的东西?

#define STRLEN (64)
char greeting[STRLEN];

strncpy(greeting,chrptr,STRLEN);

if (strlen(chrptr) > (STRLEN-1))
   greeting[(STRLEN-1)] = 0;

Use strncpy or strcpy: 使用strncpy或strcpy:

char *a = "hello world!";
int aLen = strlen(a);
char b[] = new char[aLen + 1]; // C++ version
// char* b = (char*)malloc((aLen + 1) * sizeof(char)); // C version
strncpy(b, a, aLen);
b[aLen] = '\0';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM