Passing from string to unsigned short

1.1k views Asked by At

I have 2 variables. One should be of type unsigned short array[10] (I am asked to do this), and the other will be an input from scanf that is convenient to be string.
I am passing the values one by one, from the string to the unsigned short with a for loop.
The programs works ok but I am getting warning messages.
"Warning passing argument of strcmp from incobatible pointer type" and "expected const char * but argument is of type short unsigned int". I can't seem to find how to pass from a string to unsigned short without warnings.
A short version of my program is here so that you have a clearer view.

Warnings are at lines 28,43.

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int i, j, numberofseats;
char phone[11];
char *p;
unsigned short tempphone[10];
typedef struct
{
  char fullname[40];
  unsigned short phonenr[10];
  unsigned int seatnr;
} PASSENGERS;

int main()
{
  PASSENGERS passenger[53];
  printf("Enter Passenger's Phone Nr:");
  scanf("%s", phone);
  i = 0;
  for (p = phone; *p != '\0'; p++)
  {
    (tempphone[i]) = *p - '0';
    i++;
  }
  for (j = 0; j < numberofseats; j++)
  {
    if (strcmp(tempphone, passenger[j].phonenr) == 0)
      printf("Passenger %s has Seat Nr %u already Booked", passenger[j].fullname, passenger[j].seatnr);
  }
}
1

There are 1 answers

6
John Park On

You can use memcmp or casting to char* and use strcmp. Keep in mind that memcmp requires the size of memory that will be compared as third parameter.

You can use memcmp like this,

memcmp(tempphone, passenger[j].phonenr, sizeof(tempphone));

However, it can result in wrong comparison if the size of the compared phone numbers are not the same and if one ends with the number 0. Think about the case tempphone is 12345 and passenger[j].phonenr is 1234500000. memcmp may judge the phone numbers are the same if you don't forget to initiate varibables to 0. You need another variable to keep the length of the phone number, of course, it doesn't matter if the phone numbers are fixed always.

I would keep phone numbers in array of chars instead of array of shorts and use strcmp. Phone numbers are numbers but they are not the objects of mathmatical operations like add or divide. They contains information similar to names.