Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to compare a specific string from an array of strings

Hey I am trying to learn C and just learned about array of strings
I have been tinkering around and wrote this code

char names[1][5];
strcpy(names[1], "Welp");
if (names[1] == "Welp") {
    printf("alright works\n");
}

But it doesn’t seem to work
Even after trying to figure if they are of different data types but no they both came up as pointers to char
Is there any way I can compare these two
Any help would be really appriciated

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The issue with your code lies in two main areas: indexing and copying strings, and how you’re comparing them.

Indexing out of bounds:
    In your code you declared an array char names[1][5]; which can hold only one string of up to 4 characters (plus the null terminator). However, you are trying to access names[1]. This is out of bounds since your array can only have names[0].

String comparison:
    In C, you cannot compare strings using the == operator because it compares the memory addresses (pointers) rather than the actual content of the strings.

How you can correct your code:

Here’s how you can fix these issues:

Correcting the array declaration:
    If you want to store multiple strings, make sure the first dimension matches the number of strings. For example, if you want to store two strings, you can declare char names[2][5];.

for String copying use strcpy() correctly within the bounds of your array.

for String comparison use strcmp() to compare the content of two strings.

I would recommend you to read on how Arrays work since this can happen with any value type.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading