There are a few problems with your code.
First of all, argv[i+1] is an illegal operation if you're doing i < argc in the for. You need to change i < argc to i < argc - 1 in the for.
Secondly, you are probably not comparing the strings you want. argv[0] is the string representing the path of your program; the first argument passed to your program is argv[1]. Therefore, you need to change the i = 0 in the for to i = 1.
Finally, if you only want the biggest string, you should not do any printing in the for loop. Rather, you should create two variables like max_length and max_length_idx where you would store the length and index of the largest string found so far. Then, after the for loop, your program would print out the string argv[max_length_idx].
There are a few problems with your code.
First of all, argv[i+1] is an illegal operation if you're doing i < argc in the for. You need to change i < argc to i < argc - 1 in the for.
Secondly, you are probably not comparing the strings you want. argv[0] is the string representing the path of your program; the first argument passed to your program is argv[1]. Therefore, you need to change the i = 0 in the for to i = 1.
Finally, if you only want the biggest string, you should not do any printing in the for loop. Rather, you should create two variables like max_length and max_length_idx where you would store the length and index of the largest string found so far. Then, after the for loop, your program would print out the string argv[max_length_idx].
#include <stdio.h>
#include <string.h>
int main(int argc, char *argv[])
{
int i, max_length, max_index;
max_index = 0;
max_length = strlen(argv[0]);
for(i = 1; i < argc; i++)
{
if(strlen(argv[i]) > max_length)
{
max_length = strlen(argv[i]);
max_index = i;
}
}
printf("The longest is: %s with length equal: %d\n", argv[max_index], max_length);
return 0;
}
You can't (usefully) compare strings using != or ==, you need to use strcmp:
while (strcmp(check,input) != 0)
The reason for this is because != and == will only compare the base addresses of those strings. Not the contents of the strings themselves.
Ok a few things: gets is unsafe and should be replaced with fgets(input, sizeof(input), stdin) so that you don't get a buffer overflow.
Next, to compare strings, you must use strcmp, where a return value of 0 indicates that the two strings match. Using the equality operators (ie. !=) compares the address of the two strings, as opposed to the individual chars inside them.
And also note that, while in this example it won't cause a problem, fgets stores the newline character, '\n' in the buffers also; gets() does not. If you compared the user input from fgets() to a string literal such as "abc" it would never match (unless the buffer was too small so that the '\n' wouldn't fit in it).
It returns the difference at the octet that differs. In your example '\0' < '2' so something negative is returned.
It is defined in the C standard as the difference between the first two non matching characters, but the implementation is wild. The only common point is that the return value is zero for equal strings, then respectively <0 or >0 for str1<str2 and str1>str2.
From ISO/IEC 9899:201x, §7.23.4 Comparison functions:
The sign of a nonzero value returned by the comparison functions memcmp, strcmp, and strncmp is determined by the sign of the difference between the values of the first pair of characters (both interpreted as unsigned char) that differ in the objects being compared.
But some implementations take care to return typical values as 0, 1 and -1. See i.e. the Apple implementation (http://opensource.apple.com//source/Libc/Libc-262/ppc/gen/strcmp.c):
int
strcmp(const char *s1, const char *s2)
{
for ( ; *s1 == *s2; s1++, s2++)
if (*s1 == '\0')
return 0;
return ((*(unsigned char *)s1 < *(unsigned char *)s2) ? -1 : +1);
}
EDIT:
In the Android boot library for Donut-release (https://android.googlesource.com/platform/bootable/bootloader/legacy/+/donut-release/libc/strcmp.c) the function returns 0 if strings are equal and 1 for the other 2 cases, and are used only logical operations:
int strcmp(const char *a, const char *b)
{
while(*a && *b) {
if(*a++ != *b++) return 1;
}
if(*a || *b) return 1;
return 0;
}
Hi, I'm working just for fun on a fast comparison for strings written in C, with the intent of being faster than the normal strncmp function, which is currently the code bellow
```
int fast_strncmp(const char *str1, const char *str2, int len) {
const char *final_pos = (str1 + len) - 4;
while (str1 < final_pos) {
// if characters differ, or end of the second string is reached
if (*((uint32_t *)str1) != *((uint32_t *)str2)) {
break;
}
// move to the block of characters
str1 += 4;
str2 += 4;
}
final_pos += 4;
while (str1 < final_pos) {
if (*str1 != *str2 || *str1 == 0 || *str2 == 0) {
return *str1 - *str2;
}
// move to the next pair of characters
str1++;
str2++;
}
return 0;
}
```Is there any clear problem with the code that could make it a bad option for fast string comparisons. When I wrote it a couple of weeks ago, I didn't think there could be any problem with it, but this week I was watching a couple of videos about C programming and it was mentioned that casting an array of 4 uint8_t to a uint32_t could be a problem. I'm even using this function at work and haven't had a single problem or warning, but since I'm planning to make a youtube video about it, I want to guarantee that my code won't be a problem for other people.
On top of that I've made a couple of benchmarks on the performance to be sure it really is fast, so I've compared it to strncmp and an implementation by https://github.com/mgronhol, that I found here: https://mgronhol.github.io/fast-strcmp/, which got me the following results:
EDIT: reddit was not cooperating with me posting the results text in a well formatted way, so here's the link to the file:
https://github.com/BenjamimKrug/fast_string_comparison/blob/main/results.txt
As you can see, running on the STM32 and the ESP32, my algorithm runs faster by a little compared to the fast_compare function by mgronhol, but running on my PC, it's performing terribly. Does anyone know why that is?
You can find more info about the code in my github repository where I put everything related to this test: https://github.com/BenjamimKrug/fast_string_comparison
P.S.: Sorry if this is the wrong subreddit for this kind of thing, I was going to post it on r/programming, but after reading the rules, I saw that maybe it was best to post it here.
EDIT: fixed code formatting
Use qsort. http://www.tutorialspoint.com/c_standard_library/c_function_qsort.htm It can sort an array by any criteria you desire since you write the compare function.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int compare(const void *a, const void *b)
{
printf("compare %s %s\n",a,b);
int sa = strlen((const char*)a);
int sb = strlen((const char*)b);
if (sa != sb)
{
return sa - sb;
}
return strcmp((const char*)a,(const char*)b);
}
int main()
{
char str[][100] = { "Jacob", "Alfred", "Ruess", "Reigns" };
int length = sizeof(str) / 100;
qsort(str, length, 100, compare);
int firstLen = strlen(str[0]);
for ( index= 0 ; index < 4 ; index++ )
{
if (strlen(str[index]) != firstLen)
{
break;
}
printf("%s\n",str[index]);
}
}
How about we give you the idea and you write the code? Sounds good?
So, here's what you need to do.
- Take input of four strings.
- call
strlen()once with each input string and save their lengths. - Decide which two strings to compare based on the least and second least length value.
- call
strcmp()with those two strings.
As strcmp(s1, s2) returns
an integer less than, equal to, or greater than zero if s1 (or the first n bytes thereof) is found, respectively, to be less than, to match, or be greater than s2.
you'll have the alphabatically smaller (or larger) string.
Hi, I'm working just for fun on a fast comparison for strings written in C, with the intent of being faster than the normal strncmp function, which is currently the code bellow
```
int fast_strncmp(const char *str1, const char *str2, int len) {
const char *final_pos = (str1 + len) - 4;
while (str1 < final_pos) {
// if characters differ, or end of the second string is reached
if (*((uint32_t *)str1) != *((uint32_t *)str2)) {
break;
}
// move to the block of characters
str1 += 4;
str2 += 4;
}
final_pos += 4;
while (str1 < final_pos) {
if (*str1 != *str2 || *str1 == 0 || *str2 == 0) {
return *str1 - *str2;
}
// move to the next pair of characters
str1++;
str2++;
}
return 0;
}
```Is there any clear problem with the code that could make it a bad option for fast string comparisons. When I wrote it a couple of weeks ago, I didn't think there could be any problem with it, but this week I was watching a couple of videos about C programming and it was mentioned that casting an array of 4 uint8_t to a uint32_t could be a problem. I'm even using this function at work and haven't had a single problem or warning, but since I'm planning to make a youtube video about it, I want to guarantee that my code won't be a problem for other people.
On top of that I've made a couple of benchmarks on the performance to be sure it really is fast, so I've compared it to strncmp and an implementation by https://github.com/mgronhol, that I found here: https://mgronhol.github.io/fast-strcmp/, which got me the following results:
EDIT: reddit was not cooperating with me posting the results text in a well formatted way, so here's the link to the file:
https://github.com/BenjamimKrug/fast_string_comparison/blob/main/results.txt
As you can see, running on the STM32 and the ESP32, my algorithm runs faster by a little compared to the fast_compare function by mgronhol, but running on my PC, it's performing terribly. Does anyone know why that is?
You can find more info about the code in my github repository where I put everything related to this test: https://github.com/BenjamimKrug/fast_string_comparison
P.S.: Sorry if this is the wrong subreddit for this kind of thing, I was going to post it on r/programming, but after reading the rules, I saw that maybe it was best to post it here.
EDIT: fixed code formatting
I don't think there is a way to do variable length string comparisons completely in preprocessor directives. You could perhaps do the following though:
#define USER_JACK 1
#define USER_QUEEN 2
#define USER USER_JACK
#if USER == USER_JACK
#define USER_VS USER_QUEEN
#elif USER == USER_QUEEN
#define USER_VS USER_JACK
#endif
Or you could refactor the code a little and use C code instead.
[UPDATE: 2021.01.04]
One thing that has changed since I first posted this in 2014, is the format of #pragma message.
Nowadays, the parens are required!
#pragma message ("USER IS " USER)
#pragma message ("USER_VS IS " USER_VS)
That said, the 2016 code (using characters, not strings) still works in VS2019.
But, as @Artyer points out, the version involving c_strcmp will NOT work in ANY modern compiler.
[UPDATE: 2018.05.03]
CAVEAT: Not all compilers implement the C++11 specification in the same way. The below code works in the compiler I tested on, while many commenters used a different compiler.
Quoting from Shafik Yaghmour's answer at: Computing length of a C string at compile time. Is this really a constexpr?
Constant expressions are not guaranteed to be evaluated at compile time, we only have a non-normative quote from draft C++ standard section 5.19 Constant expressions that says this though:
[...]>[ Note: Constant expressions can be evaluated during translation.—end note ]
That word can makes all the difference in the world.
So, YMMV on this (or any) answer involving constexpr, depending on the compiler writer's interpretation of the spec.
[UPDATED 2016.01.31]
As some didn't like my earlier answer because it avoided the whole compile time string compare aspect of the OP by accomplishing the goal with no need for string compares, here is a more detailed answer.
You can't! Not in C98 or C99. Not even in C11. No amount of MACRO manipulation will change this.
The definition of const-expression used in the #if does not allow strings.
It does allow characters, so if you limit yourself to characters you might use this:
#define JACK 'J'
#define QUEEN 'Q'
#define CHOICE JACK // or QUEEN, your choice
#if 'J' == CHOICE
#define USER "jack"
#define USER_VS "queen"
#elif 'Q' == CHOICE
#define USER "queen"
#define USER_VS "jack"
#else
#define USER "anonymous1"
#define USER_VS "anonymous2"
#endif
#pragma message "USER IS " USER
#pragma message "USER_VS IS " USER_VS
You can! In C++11. If you define a compile time helper function for the comparison.
[2021.01.04: CAVEAT: This does not work in any MODERN compiler. See comment by @Artyer.]
// compares two strings in compile time constant fashion
constexpr int c_strcmp( char const* lhs, char const* rhs )
{
return (('\0' == lhs[0]) && ('\0' == rhs[0])) ? 0
: (lhs[0] != rhs[0]) ? (lhs[0] - rhs[0])
: c_strcmp( lhs+1, rhs+1 );
}
// some compilers may require ((int)lhs[0] - (int)rhs[0])
#define JACK "jack"
#define QUEEN "queen"
#define USER JACK // or QUEEN, your choice
#if 0 == c_strcmp( USER, JACK )
#define USER_VS QUEEN
#elif 0 == c_strcmp( USER, QUEEN )
#define USER_VS JACK
#else
#define USER_VS "unknown"
#endif
#pragma message "USER IS " USER
#pragma message "USER_VS IS " USER_VS
So, ultimately, you will have to change the way you accomlish your goal of choosing final string values for USER and USER_VS.
You can't do compile time string compares in C99, but you can do compile time choosing of strings.
If you really must do compile time sting comparisons, then you need to change to C++11 or newer variants that allow that feature.
[ORIGINAL ANSWER FOLLOWS]
Try:
#define jack_VS queen
#define queen_VS jack
#define USER jack // jack or queen, your choice
#define USER_VS USER##_VS // jack_VS or queen_VS
// stringify usage: S(USER) or S(USER_VS) when you need the string form.
#define S(U) S_(U)
#define S_(U) #U
UPDATE: ANSI token pasting is sometimes less than obvious. ;-D
Putting a single # before a macro causes it to be changed into a string of its value, instead of its bare value.
Putting a double ## between two tokens causes them to be concatenated into a single token.
So, the macro USER_VS has the expansion jack_VS or queen_VS, depending on how you set USER.
The stringify macro S(...) uses macro indirection so the value of the named macro gets converted into a string. instead of the name of the macro.
Thus USER##_VS becomes jack_VS (or queen_VS), depending on how you set USER.
Later, when the stringify macro is used as S(USER_VS) the value of USER_VS (jack_VS in this example) is passed to the indirection step S_(jack_VS) which converts its value (queen) into a string "queen".
If you set USER to queen then the final result is the string "jack".
For token concatenation, see: https://gcc.gnu.org/onlinedocs/cpp/Concatenation.html
For token string conversion, see: https://gcc.gnu.org/onlinedocs/cpp/Stringification.html#Stringification
[UPDATED 2015.02.15 to correct a typo.]