Problems with passing constant characters when character variables are used as function arguments

When we use a char array or pointer type as a function parameter, the compiler will automatically convert the parameter to a pointer to save memory and improve efficiency, pointing to the memory address of the formal parameter, indirect reference!

Listed as the following code:

int test(char str[256]){
	return 0;
}

After compilation, the compiler converts it to a pointer:

int test(char *str){
	return 0;
}

So no matter how big your array size is, it will end up being turned into a pointer to follow the compiler bit size

This creates a problem:

int test(char str[256]){
	str [0] = 'c';
	return 0;
}
int main(){
	test("hello word");
	return 0;
	
}
If the above code runs, it will break to:
str [0] = 'c';
In this line, the reason is very simple, the str character array variable as a parameter has been turned into a char* pointer variable, and what we pass in is a constant character:
"hello word"
It does not have independent memory. It is the same memory as the instruction, also known as immediate data. For details, please refer to: In- depth understanding of "instruction set" , the segment descriptor of the code segment clearly describes that this address is read, and writing is not allowed. So when we are executing:
str [0] = 'c';

This piece of code breaks with an error. The interrupt error code is specified in the operating system kernel as: the memory here can only be read, or the memory cannot be written

So we need to change the passed parameters to variables and pass them:

int test(char str[256]){
	str [0] = 'c';
	return 0;
}
int main(){
	char str[] = "hello word";
	test (str);
	return 0;
	
}

So the code can be executed smoothly!


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325784597&siteId=291194637