Domanda

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[].

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[]?

Any help would be appreciated.

È stato utile?

Soluzione 3

something like this?

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

strncpy(greeting,chrptr,STRLEN);

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

Altri suggerimenti

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!

Use strncpy or 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';
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top