Question about arrays, strings and pointers

+1 Shlesh Tiwari · January 15, 2016
Hi all, 

Like Bucky said, the array name in itself is a pointer to its first element, and as a result we do not need to use "&" before it to get its address. 

But then if we do use "&", what is the expected output? I tried running it, and I got the same output as in the case without it. Why is this? 

Also, consider the following code:

int array1[5] = {7,21,49,70,100};
char array2[] = "Hello  there";

printf(array2);
printf(array1);
printf("\n array1 \t %p\n", array1);

The output is: 
Hello there

Why doesn't the second statement get printed? It is basically the same syntax and the same way of printing these arrays.
Similarly, among the following statements

printf(*array1);
printf("\n *array1 \t %d\n", *array1);

only the second statement prints, while the first one crashes my program. Why is this so?

Thanks in advance.

Post a Reply

Replies

Oldest  Newest  Rating
0 Laura Lee · January 17, 2016
You almost confused me by printing array2 first and array1 second.
The int array1 is not a pointer to a string of characters. Look at the argument for printf.
int printf ( const char * format, ... );

printf Is trying to interpret your pointer as a string, 
0 Linguist Llama · January 18, 2016

Like Bucky said, the array name in itself is a pointer to its first element, and as a result we do not need to use "&" before it to get its address.


You've touched on a misconception. While it's true that in most expressions, an expression denoting an array will be converted to an expression denoting the first element of the array, it's certainly not true for all.

Consider for example, that sizeof "hello world" doesn't commonly compare equal to sizeof (char *) or sizeof ("hello world"+0).

But then if we do use "&", what is the expected output?


This is another situation where an expression denoting an array is not converted to an expression denoting the first element of the array.

Don't get me wrong... The pointers will point to the same place, but the item pointed to will be different. If we declare char greeting[] = "hello world", *g = greeting; then &g will produce an expression that is a char **, while &greeting will produce an expression that is a char (*)[12].

As for your code, your compiler should be warning you about an argument mismatch.

Consider that the underlying representation of array1 might look something like "\0\0\0\7" "\0\0\0\21" "\0\0\0\49" "\0\0\0\70" "\0\0\0\100". It should now make sense why printf(array1); coincidentally prints nothing; as far as printf can see, this string is empty. If this confuses you, you need a new resource to learn from.

In printf(*array1); the expression *array is an int with the value 7. printf expects a char * that points to a string... Can you explain what string 7 points to?
  • 1

C

107,036 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator