Kyle Weller
Kyle Weller

Reputation: 2623

C pointers to characters

I am misunderstanding something about C pointers:

void putString(char* StringPtr, int length){
  for(int i=0; i< length; i++)       
  {                   
    USART_send(*StringPtr);      
    StringPtr++;
  }
}

void parseMsg(char* in_string, int str_len) {
  int i = 0;
  putString(in_string, str_len);
  for(i = 0; i <= str_len; i++) 
  {
    char* temp_pt = &in_string[i];
    putString(temp_pt, 1);
  }
}

int main(int arg) {
  char* myChar = "abcdefg";
  parseMsg(myChar, 7);
}

EDIT: In parseMsg, when I call the first putString, it works great. When I try to loop through to print each one separately, it does not. USART_send just spits out the char to my terminal.

Upvotes: 0

Views: 132

Answers (2)

bazza
bazza

Reputation: 8444

Your line char* temp = test[i]; is wrong. It makes a pointer called temp and makes it point at an address somewhere between byte 0 and byte 255 in your computer's memory. That is almost certainly a very bad thing. You probably meant char temp = test[i]; That makes a char called temp and assigns to it the value of test[i]. Also note that test[2] would also not be valid because myChar is a string with only 1 character plus the null terminator.

Upvotes: 0

Bart Friederichs
Bart Friederichs

Reputation: 33573

That's because test[i] is of type char not of type char *.

You can either assign to char:

 char temp = test[i];

or take its address:

 char *temp = &test[i];

Upvotes: 3

Related Questions