Thread: comparing char array

  1. #1
    Registered User
    Join Date
    Mar 2020
    Posts
    91

    comparing char array

    if I have

    char a[4];
    char b[4];

    is the following legal in c:

    if (b == a)

    These are NOT character strings just character arrays

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Legal - yes
    Useful - no
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Programming Wraith GReaper's Avatar
    Join Date
    Apr 2009
    Location
    Greece
    Posts
    2,739
    Indeed, using the equality operator on two arrays is perfectly valid C, although it would only produce the desired result if those two arrays were actually the exact same array in memory. That happens because C compares addresses (because the name of an array is interpreted as the address of its first element), not contents. If you want to compare the contents, you can use memcmp().
    Devoted my life to programming...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Comparing "Struct Char" with "Char in Char Array"
    By JonathanS in forum C++ Programming
    Replies: 2
    Last Post: 12-11-2012, 03:06 PM
  2. Need help for comparing a char to an array char
    By gamers18 in forum C++ Programming
    Replies: 2
    Last Post: 12-09-2012, 02:46 AM
  3. Comparing char array for two strings
    By Asbestos in forum C++ Programming
    Replies: 5
    Last Post: 02-16-2006, 12:41 AM
  4. Comparing char values in an array using 'if'
    By Judy_528 in forum C++ Programming
    Replies: 18
    Last Post: 04-25-2002, 07:52 AM
  5. ? comparing elements of a char array
    By Unregistered in forum C++ Programming
    Replies: 4
    Last Post: 09-20-2001, 07:55 AM

Tags for this Thread