I wanted the pointer p to point to the value of (var-1).Please suggest a way to solve this error.
int var = 10;
int *p;
*p =var-1;
printf("%d",*p);
To point to the value of the expression (var-1)
you need an object that will store the value.
So the only approach provided that the variable var
itself shall not be changed is the following
int var = 10;
int var2 = var-1;
int *p = &var2;
printf("%d",*p);
Or you could allocate an object of the type int dynamically where the result of the expression will be stored like
int var = 10;
int *p = malloc( sizeof( int ) );
*p = var-1;
printf("%d",*p);
//...
free( p );
According to the C Standard (6.5.3.2 Address and indirection operators)
1 The operand of the unary & operator shall be either a function designator, the result of a [] or unary * operator, or an lvalue that designates an object that is not a bit-field and is not declared with the register storage-class specifier.
And
4 The unary * operator denotes indirection. If the operand points to a function, the result is a function designator; if it points to an object, the result is an lvalue designating the object. If the operand has type ‘‘pointer to type’’, the result has type ‘‘type’’. If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined.
In the original code snippet you got a segmentation fault because the pointer p
does not point to a valid object and has indeterminate value because it was not initialized.
int *p;
*p =var-1;
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다