Syntax_Error
Syntax_Error

Reputation: 6220

Error when setting a character to a string in C

hey guys I need your help. I'm trying to extract a character from a string and set it as the 2nd element of an array of strings. Yet as usual C is giving me segmentation faults, Ive tried sprintf, strcpy, and still segmentation fault the code is:

int getwords(char *line, char *words[])
{    
    int nwords=2;  
    char *result= NULL;
    char TABS[]="\t";
    char spaces[]=" ";
    char commas[]=","; 
    result = strtok(line,TABS);
    words[1]=result[strlen(result)-1];//setting the 2nd element of the array to a char
    result[strlen(result)-1]='\0';//removing the extracted char from the string
    words[0]=result;//setting 1st element to the new modified word
    printf("the opcode is:%s and the type is:%c\n",words[0],result[strlen(result)-1]);

    return nwords;

}

e.g. If I give it "bye." it should return 2 and an array having 2 elements: 1st elem="bye" 2nd elem="." I ran some tests and found out that the error is from the statement: words[1]=result[strlen(result)-1]; Any help is welcom

Upvotes: 2

Views: 524

Answers (2)

Arafangion
Arafangion

Reputation: 11920

There are two, perhaps four mistakes in the code below, I explain two of the mistakes in the code comments:

If we assume that "line", for the purposes of explaining what happens, is "hey\tthere"...
We also assume that "words" is an array of two pointers to char.

// Find the first token, in this case "hey", and return it in "result".
result = strtok(line,TABS); // NOTE: 'line' has been modified by the function!

// Take the last character in the returned statement, which is 'y', and
// copy it to the second cell in the 'words' array, however we are supposed
// to be copying a *pointer* to char there...
words[1]=result[strlen(result)-1];

Additionally, if "line" is static and can not be changed, the first line above will crash. If "words" is not allocated or doesn't reference an array of at least two pointers to char, then the second line will crash.

If code execution gets past this point, any code that uses the "words" array will crash because the code will expect pointers, but is getting chars!

Upvotes: 2

pmg
pmg

Reputation: 108978

Are you sure words is a modifiable string?

Literal strings are unmodifiable strings. For example: this gives segmentation fault:

char *test = "forty two";
test[6] = 'T'; /* make two uppercase */

You need to show how you call getwords and the definitions of the variables involved.
I'm guessing you're passing pointers to string literals.

Upvotes: 5

Related Questions