I am trying to copy a string to an array of string. I have used these two examples before and they have worked so I don't understand why they won't work this time. I am getting a segmentation fault.

http://stackoverflow.com/a/1088667/985898
http://stackoverflow.com/a/1095006/985898

I remembered to initialize everything.

char *strings_mneumonic_table[503] = {0};
char mneumonic[20] = {0};
int start_address = 0;
int hash = 0;
        if(line[0] == 32)
        {
            printf("32 group \n");
            sscanf(line, "%s %x", mneumonic ,&start_address);
            printf("mneumonic is %s\n", mneumonic);
            printf(" hash is %d \n", hash);
            strcpy(strings_mneumonic_table[hash], mneumonic);
            //printf("under strcpy(strings_mneumonic_table[hash], mneumonic); \n");
            //hex_address_table[hash] = start_address;
            //printf("hex_address_table[hash] = start_address; \n");
            //printf("end of 32 group \n");
        }

Here is my output

hash is 2 
little start 
BIG START 
32 group 
mneumonic is START
hash is 2 
Segmentation fault (core dumped)

I figured it out. I didn't allocate memory.

The easy way (single line) is to use the char* strdup(const char* source) function.

Could you elaborate on that please? I thought those are 2 separate things. I thought the first one is declaring a char pointer to stdup. I thought the second one is const char pointer to source where you can't change it (which I need to add values to it as I run my program) and you can make a string a string array that can't change.

char* strdup
const char* source

These are your 2 choices that I am familiar with. I like the first one because its more efficient. Since I'm using C I like to be efficient :).

strs[i] = malloc(strlen("foo") + 1);
strcpy(strs[i], "foo");

char *strs[NUMBER_OF_STRINGS][STRING_LENGTH+1];

Rubberman was suggesting that you use the strdup function found in string.h.
In his post he posted the definition of the function as found in the header:
char* strdup(const char* source);
In other words strdup is a function which takes a const char* as a parameter and returns a char*.
You would use it in code like this:
char* copy = strdup(originalString);
Where originalString is the char* that you want to create a copy of.
The strdup function will create a duplicate of the string and returns a pointer to the copied string. So the variable "copy" will point to the copy of originalString.

You are using strdup as a variable. It is also the name of a C-function that copies a string. Better to do this:

        const char* source = "foo";
        char *strs[NUMBER_OF_STRINGS][STRING_LENGTH+1];
.
.
.
        strs[i] = strdup(source);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.