473,320 Members | 2,146 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

null char in c

hi,
I have this code,why is the displayed result "false"?
Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. int main()
  5. {
  6.    char name[6]="MEHMET"; /* 6 characters */
  7.    char name1[6]="MEHMET";
  8. if (strcmp(name,name1) == 0){
  9. printf("true");
  10. }else{
  11. printf("false");
  12. }
  13. return 0;
  14. }
Aug 7 '09 #1
10 3144
JosAH
11,448 Expert 8TB
Change that to:

Expand|Select|Wrap|Line Numbers
  1. char name[7]="MEHMET"; /* 6 characters */ 
  2. char name1[7]="MEHMET"; 
  3.  
That leaves room for the trailing '\0' characters that terminate strings.

kind regards,

Jos
Aug 7 '09 #2
Or better yet, you can just use this form:
char my_string[] = "the compiler will determine this string's size";

This way, you will not have to worry about knowing the actual string size as long as you don't plan on changing the string during runtime. Even better if you make it a "const char" for added safety.
Aug 7 '09 #3
thanx,but why it doesn't work when i use 6 for both arrays?i mean they both don't end with the null char so why aren't they equal??
Aug 7 '09 #4
drhowarddrfine
7,435 Expert 4TB
Since there is no terminating zero, the comparison continues past the end of the array until a zero is reached somewhere, but you don't know what data is after the last char in that array and it doesn't match so it returns false.
Aug 7 '09 #5
A character string in C has one extra NULL character after it's normal contents. In an array form, a string called "hello" would have the elements 'h', 'e', 'l', 'l', 'o' AND '\0'.
Google up "NULL terminated strings" if that doesn't make sense to you.
Aug 7 '09 #6
Banfa
9,065 Expert Mod 8TB
The most likely cause that the 7 characters ('M', 'E', 'H', 'M', 'E', 'T' and '\0') of the 2 strings are writen sequencially in memory. Note that the C compiler will write 7 characters to the given address even though you have only provided arrays of length 6.

That means that in both cases you write 1 more character than the array holds or to put it another way you write outside the array bounds. Writing outside the array bounds is undefined behaviour.

Since you program invokes undefined behaviour anything could happen, there is no point continuing or trying to explain what is happening.

However assuming you ignore my last statement and continue then like I say those 2 arrays probably appear sequencially in memory. It allocates them and then writes 'M', 'E', 'H', 'M', 'E', 'T' and '\0' to the first one. Note the '\0' is written outside the bounds of the array and inside the next variable so when the next array is written the first 'M' overwrites the '\0' of the first array. You end up with the memory contents:

'M' 'E' 'H' 'M' 'E' 'T' 'M' 'E' 'H' 'M' 'E' 'T' '\0'

Note the presence of only 1 zero terminator, one of the strings will appear to have the contents to both to a function like strcmp.

Also note this is all conjecture, I have seen it happen on 1 system but like I said originally undefined behaviour has been invoked, anything could happen.
Aug 7 '09 #7
JosAH
11,448 Expert 8TB
@Banfa
That is not true, e.g. the following code snippet stores only 2 chars in the array:

Expand|Select|Wrap|Line Numbers
  1. char array[2]= "foo";
  2.  
I don't have the Standard with me right now but it explicitly mentions this behaviour.

kind regards,

Jos
Aug 8 '09 #8
Banfa
9,065 Expert Mod 8TB
@JosAH
DOH ! :D Apart from the fact that it is always a mistake to try and analyse undefined behaviour I perhaps should have qualified all of that with the platform on which I observed that behaviour (I certainly intended to) and that that was just my interpretation.

Thanks for the catch Jos, I guess the important point of this is that you should always make sure your arrays are large enough to hold the data you are putting in them and that particularly when calculating the size of a character array tohold a zero terminated string that you don't forget to include space for the zero terminator.
Aug 8 '09 #9
It's best to do const char* name = "MEHMET"; instead, as it adds the trailing '\0' and it's good practice to not play with implicit casts when you're not sure what might happen :)
Aug 8 '09 #10
@Troy Martin
In that way, you will be holding a pointer to the statically allocated character array and not the array itself. While syntax while there are no differences, the C standard makes no notion of how this should be handled and may, among other things make it less likely for the compiler to optimize your code. Any literal string has "\0" at the end unless you manually init the array character by character, which is why there are no (functional) differences to using this over const char name[] = "MEHMET";.
In fact, your code does have an implicit cast from char[] to char*. On the other hand, I'm almost certain that the C/C++ standards state that all string literals must always exist during runtime, so this form should not cause any errors unless you use this var in some static external object/var.
Aug 9 '09 #11

Sign in to post your reply or Sign up for a free account.

Similar topics

16
by: mike79 | last post by:
Hi all, I have a the following simple piece of code which has taken me hours to try and sort out the problem, but still unable to find what is wrong. void main( void ) { char (*string);...
102
by: junky_fellow | last post by:
Can 0x0 be a valid virtual address in the address space of an application ? If it is valid, then the location pointed by a NULL pointer is also valid and application should not receive "SIGSEGV"...
64
by: yossi.kreinin | last post by:
Hi! There is a system where 0x0 is a valid address, but 0xffffffff isn't. How can null pointers be treated by a compiler (besides the typical "solution" of still using 0x0 for "null")? -...
35
by: fcvcnet | last post by:
Hi, This is c code , but the question is same to c++ £¨new/delete£©. char* p = malloc(10); strcpy(p, "hello"); printf("%s\n", p); free(p); // free just add p to the free list of memory, and...
15
by: khan | last post by:
Hi, I read that pointer representation can non-zero bit pattern, machine specific.Compiler when comes accross value '0' in pointer context, converts it to machine specific null pointer...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
0
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.