0

I have an interesting problem.

I define,

typedef char *string;

char array[10];    
string buf[10];  
i=0;  
while(1){    
  array=<assign_string>       
  buf[i]= array;        
  i++;
}    

At each iteration i assign different strings. For instance, buf[0] should be "1111111111" buf[1] should be "2222222222" and so on. However when i assign "2222222222" when i=1, buf[0] also changes to "2222222222". What could be the problem?

0

3 Answers 3

1

The problem is that all entries in buf point to the same string - the one named array. So changing array will affect all buf entries.

You could fix this by allocating a new string for every iteration, e.g. your pseudo-code would become:

string buf[10];  
i=0;  
while(1){    
  buf[i]= strdup( <array_string> );
  i++;
}

Make sure to free() all the strings when you're done using them.

Sign up to request clarification or add additional context in comments.

1 Comment

btw, your "typedef char *string;" has hidden the problem. That's exactly why a "char *" is NOT a string in C. In C, there is no data type "string".
0

You are probably not allocating a new string for each entry in buf. Instead you are saving a reference to the same string in each buf entry.

Comments

0

When you do buf[i]=array; you put the address of your char array[10] into buf[i]. No suprise, each buf[i] has the same address and the same value.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.