-2

I have the following snippet that gives me a warning when compiling (the code works anyway):

char *x_first_name, *x_last_name, *x_address, *x_zip;

const size_t firsts_count = sizeof(firsts) / sizeof(firsts[0]);
const size_t lasts_count = sizeof(lasts) / sizeof(lasts[0]);
const size_t streets_count = sizeof(streets) / sizeof(streets[0]);
const size_t zips_count = sizeof(zips) / sizeof(zips[0]);

srand(time(NULL));

x_first_name = firsts[rand() % firsts_count]; // line 69
x_last_name = lasts[rand() % lasts_count]; // line 70
x_address = streets[rand() % streets_count]; // line 71
x_zip = zips[rand() % zips_count]; // line 72

Warning compiling:

authorize.c: In function 'main':
authorize.c:69: warning: assignment discards qualifiers from pointer target type
authorize.c:70: warning: assignment discards qualifiers from pointer target type
authorize.c:71: warning: assignment discards qualifiers from pointer target type
authorize.c:72: warning: assignment discards qualifiers from pointer target type

firsts, lasts, streets and zips are declared as:

const char *firsts[] = {
        "Asgar",
        "Aadit",
        "Aanand",
        "Aaron"
};

What am I doing wrong?

bsteo
  • 1,738
  • 6
  • 34
  • 60

2 Answers2

3

As the compiler states, you're discarding a qualifier (const in this case) from a pointer upon assignment.

This happens when you assign a char * the value of a const char *.

Hasturkun
  • 35,395
  • 6
  • 71
  • 104
1

firsts, lasts,streets are array so operation like firsts[rand() % firsts_count]; will return a value which is const char* in your case.

But you are trying to collect these values in x_first_name and x_last_name variables which are char*(pointer to char).so in assignment it is loosing its const nature.

Dayal rai
  • 6,548
  • 22
  • 29
  • Yes, I got it, I will use just "char*", I forgot I defined those arrays in my headers as "const char*", I looked only in the main code and overlooked the header files. – bsteo Jun 13 '13 at 13:21