csounder5
csounder5

Reputation: 55

pointer to integer type modeled on pointer to typedef type

For didactic motives, i want to build a pointer to an integer, and i take a model from a pointer to a typedef (working example below in (1) ) but the example at (0) gives the mesage "error: syntax error before '=' token" at ptr =&a; and i can not understand why. I will thank the correction.The code is:

(0) //failing code

#include <stdio.h>

typedef int  *ptr;

int main(){
int a;
ptr =&a;      //<-----"error: syntax error before '=' token"
a =2;
printf("%d\an",a);
return 0;
}

(1) //working code

#include <stdio.h>

typedef struct sum {
int a,b,c;
} mytype;

int main(){

mytype  sum_operation;    
mytype *ptr;

ptr = &sum_operation;

(*ptr).a = 1;
(*ptr).b = 3;       

(*ptr).c =(*ptr).b + (*ptr).a  ;
printf("%d\n",(*ptr).c);

return 0;
}

Upvotes: 0

Views: 1403

Answers (2)

rullof
rullof

Reputation: 7442

This syntax:

typedef int  *ptr;

Is not a pointer to a typedef. You're defining a new type named ptr which is a pointer to an integer.

This syntax:

ptr = &a;

is equivalent to:

int* = &a; // error: syntax error before '=' token

Which is incorrect as you must specify a variable name:

ptr myPointer = &a

which is equivalent to:

int* myPointer = &a;

Upvotes: 4

user2357112
user2357112

Reputation: 282026

If you want to declare a variable, you need to give it a name:

ptr b = &a;
//  ^ This part.

Upvotes: 0

Related Questions