Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "int* p=+s;" do?

I saw a weird type of program here.

int main() {     int s[]={3,6,9,12,18};     int* p=+s; } 

Above program tested on GCC and Clang compilers and working fine on both compilers.

I curious to know, What does int* p=+s; do?

Is array s decayed to pointer type?

like image 885
msc Avatar asked May 30 '18 06:05

msc


People also ask

What does int * Address mean?

so p= (int *) &i means p is storing the address of i which is of type char but you have type cast it, so it's fine with that. now p is point to i. *p = 123455; // here you stored the value at &i with 123455. when you'll print these value like. print (*p) // 123455.

What do you mean by a pointer to a pointer can this be extended PDF?

A pointer to a pointer is a form of multiple indirection, or a chain of pointers. Normally, a pointer contains the address of a variable. When we define a pointer to a pointer, the first pointer contains the address of the second pointer, which points to the location that contains the actual value as shown below.

How do you find the length of a string with a pointer?

The strlen() Function The strlen() accepts an argument of type pointer to char or (char*) , so you can either pass a string literal or an array of characters. It returns the number of characters in the string excluding the null character '\0' .


2 Answers

Built-in operator+ could take pointer type as its operand, so passing the array s to it causes array-to-pointer conversion and then the pointer int* is returned. That means you might use +s individually to get the pointer. (For this case it's superfluous; without operator+ it'll also decay to pointer and then assigned to p.)

(emphasis mine)

The built-in unary plus operator returns the value of its operand. The only situation where it is not a no-op is when the operand has integral type or unscoped enumeration type, which is changed by integral promotion, e.g, it converts char to int or if the operand is subject to lvalue-to-rvalue, array-to-pointer, or function-to-pointer conversion.

like image 139
songyuanyao Avatar answered Sep 21 '22 13:09

songyuanyao


Test this:

#include <stdio.h> int main(){     char s[] = { 'h', 'e', 'l', 'l', 'o' , ' ', 'w', 'o', 'r', 'l', 'd', '!'} ;     printf("sizeof(s) : %zu,  sizeof(+s) : %zu\n", sizeof(s), sizeof(+s) ) ; } 

On my PC (Ubuntu x86-64) it prints:

sizeof(s): 12,  sizeof(+s) : 8 

where

12 = number of elements s times size of char, or size of whole array  8 = size of pointer 
like image 35
Khurshid Normuradov Avatar answered Sep 18 '22 13:09

Khurshid Normuradov