Quote:
Originally Posted by Markus
Can you explain why line 10 does not require the address-of operator, while 12 does?
Line numbers changed to match redacted code listing. [donbock]
-
struct computer {
-
int cpu_speed;
-
char cpu_type[16];
-
};
-
typedef struct computer SC;
-
-
void DataReceive(SC *ptr_s)
-
{
-
printf("CPU Type: ");
-
scanf("%s", ptr_s->cpu_type);
-
printf("CPU Speed: ");
-
scanf("%d", &ptr_s->cpu_speed);
-
}
From scanf documentation:
- Conversion specifier s: the corresponding argument shall be a pointer to the initial character of an array large enough to accept the sequence and a terminating null character, which will be added automatically.
- Conversion specifier d: the corresponding argument shall be a pointer to integer.
The argument for the %s conversion specifier is a char array. An array specifier is almost always equivalent to a pointer to the first element of the array; hence ptr_s->cpu_type is the same as &ptr_s->cpu_type[0] so it is a pointer to char as expected by scanf.
The argument for the %d conversion specifier is the address of an int; hence it is a pointer to int as expected by scanf.
By the way, you might prefer the following to preclude overflowing the cpu_type array:
- scanf("%15s", ptr_s->cpu_type);