By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
454,134 Members | 1,195 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 454,134 IT Pros & Developers. It's quick & easy.

More problems with string manipulation and seg faults

P: 20
Alright, here's what I'm working on now. It's supposed to go through an inputted list of words, pick out actual words and create a numbered list of them, then, where it finds a number in the list, go back in the list from that number, replace it with a word, augment the list accordingly and continue.

Anyways, here's what I have:
Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <ctype.h>
  4. #include <stdlib.h>
  5.  
  6. int main ()
  7. {
  8.     char line[100];
  9.     char word[100];
  10.     char tword[20];
  11.  
  12.     int k, index, nwords = 0, j;    
  13.  
  14.     gets(line);
  15.  
  16.     while(line[0] != '0')
  17.     {
  18.         if(isalpha(line[k]))     
  19.         {
  20.             j = 0;
  21.             while (isalpha(line[k]))
  22.             {
  23.                 tword[j] = line[k];
  24.                 j++;
  25.                 k++;
  26.             }
  27.             tword[j] = '\0';
  28.             strcpy(word[nwords], tword);
  29.             nwords++;
  30.         }
  31.         else if(isdigit(line[k]))
  32.         {
  33.             index = atoi(line[k]);
  34.             k++;
  35.             if(isdigit(line[k]))
  36.             {
  37.                 index = index * 10  + atoi(line[k]);
  38.                 k++;
  39.             }
  40.             printf("%s", word[nwords - index]);
  41.             strcpy(tword, word[nwords-index]);
  42.             for(j  = index + 1; j < nwords; j++)
  43.             {
  44.                 strcpy(word[j - 1], word[j]);
  45.             }
  46.             strcpy(word[nwords - 1], tword);
  47.         }
  48.         else
  49.         {
  50.             printf("%c", line[k]);
  51.             k++;
  52.         }
  53.     gets(line);    
  54.     }
  55.     return 0;
  56. }
The problem is that I get segmentation faults when executing. Anybody see what I'm missing?
Mar 7 '07 #1
Share this Question
Share on Google+
3 Replies


Banfa
Expert Mod 5K+
P: 8,916
k is never initialised
Mar 8 '07 #2

P: 20
Yeah, I noticed that right after I posted. However, I've changed that now, to no avail.
Mar 8 '07 #3

Expert 100+
P: 1,510
an obvious problem is line 28
Expand|Select|Wrap|Line Numbers
  1.             strcpy(word[nwords], tword);
  2.  
word[] is an array of char, it should be an array of char* or char[], e.g.
Expand|Select|Wrap|Line Numbers
  1.     char word[100][20];
  2.  
Mar 8 '07 #4

Post your reply

Sign in to post your reply or Sign up for a free account.