Changing a string pointer in C -



Changing a string pointer in C -

this question has reply here:

c function alter string using pointer 3 answers

apparently i'm fellow member of big club doesn't understand c-style pointers correctly. here's program:

void changethestring (const char * thestring) { thestring = "string two"; } int _tmain(int argc, _tchar* argv[]) { const char * teststring = "string one"; changethestring(teststring); printf("the string is: %s.\n", teststring); homecoming 0; }

my intent changethestring() should cause pointer point "string two". logic i'm giving function pointer. function should able alter pointer point different area in memory. , alter should persist outside function.

yet that's not happens. in printf() statement, string still "string one".

can explain why is, what's happening under covers, , how can write function changethestring() alter string pointer points?

you should give pointer pointer instead of pointer. reason in c, arguments sent value. in order alter value of variable pointer, need send pointer variable, therefore, pointer pointer.

update: can define string literal outside of changethestring function, it's not needed, because string literals stored in global string table whole lifetime of program. both this:

const char* string_two_literal = "string two"; void changethestring (const char ** thestring) { *thestring = string_two_literal; } int _tmain(int argc, _tchar* argv[]) { const char * teststring = "string one"; changethestring(&teststring); printf("the string is: %s.\n", teststring); homecoming 0; }

and this:

void changethestring (const char ** thestring) { *thestring = "string two"; } int _tmain(int argc, _tchar* argv[]) { const char * teststring = "string one"; changethestring(&teststring); printf("the string is: %s.\n", teststring); homecoming 0; }

should work.

c pointers

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -