C function and char *

129 views Asked by At

I have this function:

void print_pol(char* pol); //or char[]
    printf("%s", pol);
}

In main(), I call this function as below

print_pol("pol1");

But I didn't allocate memory for char* pol in the program. So how is this possible? I know that a pointer must point to something.

4

There are 4 answers

0
juanchopanza On BEST ANSWER

"poll1" is a string literal with type length-6 array of char, char[6]. The data itself is stored in read-only memory. Your function parameter pol may look like an array, but it is adjusted to char*, giving you this:

void print_pol(char* pol){ ...

When you pass it the literal to the function, it decays into a pointer to its first element. No allocation is required on your side.

0
Sourav Ghosh On

In your code "pol1" is called a string literal. During compilation time, this data is stored into some memory area (usually read-only memory, which cannot be altered, or atleast any attempt to alter the contents will result in UB) which is allocated by the compiler itself.

When you use it, you essentially pass the base address of the string literal and collect it into a char * ( same as char [] in case of usage in function parameter). There is no need for any allocation from your side.

0
Rndp13 On
void print_pol(char pol[])
{        
  printf("%s", pol);
}


int main()
{
  print_pol("pol1");
  return 0;
}

Once you call the function print_pol("pol1"), in the function definition it is converted to a pointer and print_pol(char* pol); char *pol points exactly to the first location of the character array.

Hence no memory is needed or allocated for the same.

0
barak manos On

The compiler compiles print_pol("pol1") as follows:

  • Allocate a block of 5 consecutive characters in a read-only memory segment of the executable image, containing the characters 'p', 'o', 'l', '1' followed by the null character ('\0').

  • Pass the memory address of that block to function print_pol.

So to answer your question, the compiler allocates this memory.