+ 2

Difference between char *str and char[] str.

Which one is recommanded

4th Jul 2021, 7:00 PM
Rishi
Rishi - avatar
9 ответов
+ 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.
4th Jul 2021, 7:32 PM
Jan
Jan - avatar
+ 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.
5th Jul 2021, 11:57 AM
Jan
Jan - avatar
+ 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.
5th Jul 2021, 5:27 PM
Jan
Jan - avatar
+ 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
6th Jul 2021, 8:17 AM
DHANANJAY PATEL
DHANANJAY PATEL - avatar
+ 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.
8th Jul 2021, 11:35 AM
Jan
Jan - avatar
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.
5th Jul 2021, 6:46 PM
Jan
Jan - avatar
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.......
5th Jul 2021, 7:41 PM
Jan
Jan - avatar
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.
5th Jul 2021, 8:15 PM
Jan
Jan - avatar
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.
7th Jul 2021, 6:38 PM
Jan
Jan - avatar