0

Im trying to copy substrings from one char* to another, when I printf(%c) it shows the chars printing, but at end of add method, i use printf(%s) to print entire string and nothing is printing out. Any help is appreciated - also perhaps a better method for substrings in C than char by char?

Code below:

int aliasCount;

typedef struct Alias {
  char* alias;
  char* actual;
  struct Alias* next;
}Alias;

Alias* aliasHead;

void addAlias(char* new);

addAlias method

void addAlias(char* new)
{
  strip(new);
  Alias* newAlias = (Alias*)malloc(sizeof(Alias));

  //Get start-end position for alias
  int start=0; int end=0; int countSpace=0;
  for(int i = 0; i < strlen(new); i++)
  {
    //Check for space
    if(new[i]==' ')
    {
        printf("found space %d\n",i);
        countSpace++;
        if(countSpace==1)
        {
          start=i;
        }
        else if(countSpace==2)
        {
          end=i;
          break;
        }
    }
  }

  //malloc memory
  newAlias->next=NULL;
  newAlias->alias=(char*)malloc(sizeof(char)*(end-start));
  newAlias->actual=(char*)malloc(sizeof(char)*(strlen(new)-end+1));

  //Get substring, 
  //Copy char by char from alias to node
  for(int i = 0; i < strlen(new); i++)
  {
    if(i>start && i<end) //Alias
    {
        newAlias->alias[i] = new[i];printf("'%c'",newAlias->alias[i]);
    }
    else if(i>end) //Actual command
    {
        newAlias->actual[i] = new[i];printf("'%c'",new[i]);
    }
  } 
  printf("%s\n%s\n",newAlias->alias,newAlias->actual);

  if(aliasCount==0)
  {
    aliasHead = newAlias;
  }
  else
  {
      Alias* curr = aliasHead;
      for(int i = 0; i < aliasCount; i++)
      {
        curr=curr->next;
      }
      curr->next = newAlias;
  }
  aliasCount++;
  printf("%s\n%s\n",aliasHead->alias,aliasHead->actual);
}
Kairan
  • 5,342
  • 27
  • 65
  • 104

1 Answers1

1

Your indices are wrong; you copy the range from new[start+1] to new[end-1] into the range from alias[start+1] to alias[end-1], when you actually need to copy it into the range from alias[0] to alias[end-start-2]:

        newAlias->alias[i-start-1] = new[i];printf("'%c'",newAlias->alias[i]);

and similarly (mutatis mutandis) for actual.

ruakh
  • 175,680
  • 26
  • 273
  • 307
  • Yes thanks, its always something you learned way back in the early days of programming that throws you off isn't it. – Kairan Oct 23 '12 at 22:36