+ 2
Difference between char *str and char[] str.
Which one is recommanded
9 Respuestas
+ 3
You shouldn't use a pointer if you are initializing only one string, but you can use pointer if it's a hole array of strings.
+ 2
Martin Taylor I agree with the dynamic memory location, but it's not necessary if it only is a simple text string, and by the way, a pointer string sometimes behaves different depending on what functions or methods you are using. It's not always the best thing to declare a pointer string, just because you can.
+ 1
Martin Taylor Of course, str1 and str2 are comparable. You have misunderstood something here when I talk about how pointer strings sometimes behave differently.
+ 1
Rishi,
char str[ ] is constant char pointer, holds constant address, can't be modified
char * s is varient pointer to char address space, whatever address it holds can be easily modifiable as well as reassigned
+ 1
Martin Taylor I actually found out why strcmp failed to compare two strings properly in some cases. I forgot to add the NULL character, but it also means that strncmp does the job if you forget to add that NULL character.
0
By the way, I have experienced some weird things a few times in code operations with strcmp where I had to use strncmp instead, and I have also experienced strcpy didn't work as expected unless I changed something in the declaration of a string array.
0
Martin Taylor Well, then you could probably explain why I once experienced strcmp wouldn't compare a row of strings correctly if the next string in the row was shorter than the prior string. It only worked when I used strncmp instead. I think it was with palindrome words it occured.
Maybe it's a bug in the gcc compiler, I don't know.......
0
Martin Taylor The string array I was talking about was a char pointer array, that I had to change to a normal multi-dimentional array.
0
Martin Taylor I have never had problems with strncmp, it always works, but there had been a few times where strcmp didn't work as expected, but I will take a look at your example and compare it with the few times I had a problem with strcmp.