Is the memory allocated for the character array given as an actual parameter in the function call?

I just want to know if the character array specified as an actual parameter at the time of the function call is saved in some memory. Example:

void printIt(char* ptr) {
......
}

      

This function is called like this:

printIt("hallo");   

      

This works great. But if we pass in an integer and receive it as an int * it won't work as we don't allocate memory for it. So does the compiler automatically allocate memory for the character array passed as an argument?

+3


source to share


3 answers


Edited to reflect input of comments:



Where is it stored in memory, you ask? The string "hallo" is stored as a string literal in read-only memory. Therefore, a pointer (which is stored on the local stack for your printit () method) must be passed so that the method can find the string. As other people have pointed out, the pointer refers to the first letter of the string, which is stored as a character array. The reason you are not passing a pointer to int is because you are passing an actual value, which is then stored locally on the stack.

0


source


Using

printIt("hallo");

      

you are sending the base address of the string literal "hello" to the function printIt()

, and you are receiving the same in char* ptr

. ptr

indicates the base address "hallo"

. Separate memory is not allocated as such.



In the same logic, sending int

and receiving it int *

will not work. You need to get through &<some int>

.

Note: the variable itself char * ptr

has local scope within the function printIt()

.

0


source


When you pass a string to a function, the ptr pointer variable will point to h

because that is the starting position of the string and it will print a NULL character. 4 bytes will be allocated for ptr on a 32 bit system, so it will get the string.

0


source







All Articles