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
  • #define null "null" what the hell is this? Commented Dec 10, 2015 at 19:38
  • 1
    Where's the allocation? Commented Dec 10, 2015 at 19:39
  • thanks. i change my question. i want to make an string array like this: hash_table[0]-->"sunday" hash_table[1]-->"monday" how to make it? Commented Dec 10, 2015 at 20:15

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.