linofex
linofex

Reputation: 340

C function and char *

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.

Upvotes: 2

Views: 102

Answers (4)

barak manos
barak manos

Reputation: 30136

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.

Upvotes: 0

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

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.

Upvotes: 1

Rndp13
Rndp13

Reputation: 1122

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.

Upvotes: 0

juanchopanza
juanchopanza

Reputation: 227390

"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.

Upvotes: 4

Related Questions