Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

printf() prints whole array

Let's assume I have the following code in my C program:

#include <stdio.h>

void PrintSomeMessage( char *p );

int main(int argc, char *argv[]) {
    char arr[10] = "hello";
    PrintSomeMessage(&arr[0]);
    return 0;   
}

void PrintSomeMessage(char *p)
{
    printf("p: %s",p);
}

Why the output of this would be the whole word "hello" instead of a single character "h"?

I understand, though, that if I put a "%c" in the formatter, it will print just a single letter. But still, the memory address for each letter in this address is different. Please, someone explain it to me?

like image 981
NullPointerException Avatar asked Jun 06 '13 12:06

NullPointerException


People also ask

How do I print an entire array?

We cannot print array elements directly in Java, you need to use Arrays. toString() or Arrays. deepToString() to print array elements. Use toString() method if you want to print a one-dimensional array and use deepToString() method if you want to print a two-dimensional or 3-dimensional array etc.

Can we print a whole array without loop?

Ya, we can. If the array size is fixed, for example if the array's size is 6. Then you can print the values like printf(a[0]) to printf(a[5]).


1 Answers

But still, the memory address for each letter in this address is different.

Memory address is different but as its array of characters they are sequential. When you pass address of first element and use %s, printf will print all characters starting from given address until it finds '\0'.

like image 101
Rohan Avatar answered Sep 19 '22 16:09

Rohan