47aravind
47aravind

Reputation: 13

Function with character pointer as arguments

In the following code when the function print_uart transfer the string "Hello world" whats exactly received in *s?Is it the character H or the address of the memory where the string "Hello World" is stored??

volatile unsigned int * const UART0DR = (unsigned int *)0x101f1000;
void print_uart0(const char *s)
{
  while(*s != '\0')  
  {                                 /* Loop until end of string */
    *UART0DR = (unsigned int)(*s);  /* Transmit char */
    s++;                            /* Next char */
  }
}
void c_entry() 
{
    print_uart0("Hello world!\n");
}

Upvotes: 0

Views: 73

Answers (3)

AndersK
AndersK

Reputation: 36082

The argument s points to the first character of the string literal "Hello world!\n". A string is by default terminated with \0 so the while loop

while(*s != '\0')  
{                                 /* Loop until end of string */
  *UART0DR = (unsigned int)(*s);  /* Transmit char */
  s++;                            /* Next char */
}

copies one character at a time H,e,... to the same address 'UART0DR'

Upvotes: 0

bottaio
bottaio

Reputation: 5093

Compiler takes all your string constants and allocate memory for them. In s you have a place in memory where it is stored and by *s you get first character of this string.

It is also important to note that using exactly same string constants would probably point to the same place in memory -> such optimization saves some memory.

Upvotes: 0

Steve Summit
Steve Summit

Reputation: 47952

s is a pointer to the memory where the string "Hello World" is stored.
*s is the first character, 'H'.

Upvotes: 1

Related Questions