1
#define null "null" //its declared on top

int hash_size=100;
char *hash_table[hash_size];

int i;

for(i=0;i<hash_size;i++){
    strcpy(hash_table[i],null);// it doesn't works. WHY!
    //hash_table[i]=null; it works
}

i created a string pointer array. And i want to assign all elements with "null". But strcpy function doesn't works. Why?

3 Answers3

2

hash_table is an array of pointers BUT you have not initialized them to point anywhere. You have not initialized the pointers in the array of pointers.

You can say

hash_table[i] = null;

and that will work.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
nicomp
  • 4,344
  • 4
  • 27
  • 60
2

You could do that the following way

#define null "null" //its declared on top

int hash_size=100;
char *hash_table[hash_size];

int i;

char *p = null;

for(i=0;i<hash_size;i++){
    hash_table[i] = p;
}

In this case all elements of hash_table would point to the same string literal "null".

You may not copy the string literal because 1) elements of the array are not initialized and 2) do not point to memory extents large enough to store a copy of the string literal.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
2

You only created an array pointers. But those pointers don't point to any valid memory - they are uninitialized. This is undefined behaviour.

The macro null doesn't make much sense either. If you want to initialize the pointer to NULL pointer then you can simply do:

char *hash_table[hash_size] = {0}; 

or if you really want each pointer to point to the string literal "null" then you can assign it:

for(i=0;i<hash_size;i++){
    hash_table[i]=null;
}

The assignment works because each of the pointers in the array is simply pointing at the string literal and point to the same string literal too.

If you want to be able to modify the memory that the pointers point to then you need to allocate memory:

for(i=0;i<hash_size;i++){
    hash_table[i] = malloc(sizeof("null"));
    if (hash_table[i]) { 
       */ error */
    }
    strcpy(hash_table[i],null);
}

And free() the pointers in a similar loop once you are done.

P.P
  • 117,907
  • 20
  • 175
  • 238