sizeof vs strlen in long running programs [closed] - c

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Which of these is faster and can be used in programs which runs 100s of times in a loop (for size of strings)?
sizeof - it is a macro and a compile time expression.
or
strlen - it's run time expression.
In my mind I want to avoid strlen as it's a function and calling it again and again might slow things down - Am I correct?

These do not do the same thing.
sizeof is an operator which, in most cases, is evaluated at compile time. It gives the size in bytes of a variable, including arrays and structs. In contrast, strlen is a function which returns the length of the string passed to it.
For example:
char str[100] = "hello";
printf("size = %zu\n", sizeof str); // prints 100
printf("len = %zu\n", strlen(str)); // prints 5
That being said, if you're looking to optimize something like this:
int i;
for (i=0; i<strlen(str); i++) {
...
}
You should do this instead:
int i;
int len = strlen(str);
for (i=0; i<len; i++) {
...
}

If your strings are not string literals or arrays then strlen is your only choice. Either way, it will be fast—strlen is usually very heavily optimized.

Related

Size of char Array doesn't change(C) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Somehow my program outputs the same size no matter how long the array gets, do you know what i did wrong?
char charArray[] = "STRING";
int size = sizeof(charArray) / 2 - 1;
printf("%d", size);
Output: 3
(i have to create a program which finds a string in another string thats why i am substracting 1 at the end to find the length of the word i want to find)
If you just want to get the length of your string, you could use strlen from the string library, of implement your own one:
size_t my_strlen(const char *str)
{
size_t i = 0;
while (str[i] != '\0')
i++;
return (i);
}
with this function, my_strlen("STRING") will return 6.

Which is quicker between printf %s and for loop %c [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Please I'd like to know which is better/quicker to process between:
printf("%s", foo);
and
for(int i = 0; i < len; i++)
printf('%c', foo[i]);`
I have noticed that the output is not always the same.
The single call printf("%s", foo); is most likely faster. You only make one function call to printf instead of n function calls, each of which has to parse the format string.
Even if the latter was faster, the former is still preferred because it is clearer to the reader.
Performance test it. Trying to come up with any rule that A is faster than B is bad practice. The assumption will become incorrect over time or in slightly different scenarios. Always performance test when optimizing.
Write a test case and test it with a high precision timer. Make sure your performance timer has a high enough granularity to show differences. On Windows you can use QueryPerformanceCounter. Googling that function should get you started.
Note that there is a syntax error in: for(int i = 0; i < len; i++) printf('%c', foo[i]);. It should read:
int len = strlen(foo);
for (int i = 0; i < len; i++)
printf("%c", foo[i]);
This loop, assuming the length of foo fits in a int, is quite inefficient. printf("%s", foo); is very likely faster than that, but if you have noticed different output, there is something fishy going on... Maybe len was not computed properly.
Note also that you could write a potentially more efficient version:
for (int i = 0; i < len; i++)
putchar(foo[i]);
And you could also improve on printf("%s",foo); with this variant:
fputs(foo, stdout);
But as always, you should test and benchmark on your system to measure actual performance. Some compilers will optimize the printf("%s", foo); into fputs(foo, stdout); automatically.
The statement without loop is probably faster than the statement with loop.
Using for loop
for(int i = 0; i < len ; i++)
printf("%c", foo[i]) ;
In every iteration, i is compared with 'len' and i is incremented after every character is printed.
Without loop
printf("%s", foo) ;
foo here is basically a pointer to string and it will go on printing every character after foo[0] until a '\0' character (or terminating character) is found.
So, in the 2nd case, we save the time to update i and access foo[i] with respect to foo[0].
To add a disclaimer, the actual performance testing might lead you to results that would depend on the compiler and the operating system you are working on.

Fill char *array from 0 to x [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
i have a problem with a char *array in c (gcc linux)
on debian it works, but on another systems (yocto,raspbian) come a segmentation fault
The working Code in Debian:
char *myarray;
for (i=0;i<999;i++){
printf(myarray, "%i", i);
//do something with string to compare in file
}
But this Code fault on another Systems, i have tried to make a Array:
char *myarray[999]={"0","1","2"};
for (i=0;i<999;i++){
//do something with string[i] to compare in file
}
This Code also works but i dont like to fill a array from hand to "999"
I haven't found a method to make a char *string[arr] from "0"-"999" in a loop
Well , you can use sprintf-
char *array[1000];
for(int i=0;i<1000;i++){
array[i]=malloc(10*sizeof(**array)); //allocate memory to pointer
if(array[i]!=NULL){ //check return of malloc
sprintf(array[i],"%d",i);
}
}
Note- Just remember to free the allocated memory.
It's very unclear what you're after.
If you want to build an array holding the strings "0" through "999", you can do it using snprintf():
char array[1000][4]; /* Wastes some space, but not a great deal. */
for(int i = 0; i < 1000; ++i)
snprintf(array[i], sizeof array[i], "%d", i);
then you can print e.g. 452 like so:
printf("452 is %s\n", array[452]);

For looping in C confused [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
What problem if I use strlen() in the condtion of for loop.
char s[i];
for (int i = 0; strlen(s); i++)
So if I use upper code there took a lot of time.
But if I store the value of strlen of s it took little time inspect to upper code.
What difference between these?
You should not use i < strlen(s) as a condition because the length of the string in s gets recomputed for each iteration of the loop. It is better to use a separate variable and compute the length in the initialization part:
for (size_t i = 0, len = strlen(s); i < len; i++) {
...
}
Note that your definition of s looks like a typo: char s[i];. What variable i are you referring to? what would be its value before the beginning of the for loop that defines a new i variable?
EDIT
After reformatting your code, I realized there is even more confusion:
for (int i = 0; strlen(s); i++)
This for loops iterates as long as string s is not empty. Is this your intent? Do you modify s inside the loop? s is uninitialized, the test invokes undefined behavior. Do you initialize s in code you did not post between the definition and the for loop? If you do, it would still be more efficient to write such a loop this way:
for (int i = 0; *s != '\0'; i++)
The condition is evaluated before every iteration of the loop.
C strings are just an array of characters, then a NULL. So to work out the length you have to start at the start and inspect every character from there until you find the NULL.
So in complexity terms, strlen is O(n). Your for is also O(n). If you check the strlen every time then your implementation is O(n*n). If you work it out once in adavance then yours os O(n). Try it with longer ss to see a much bigger difference.

Printing one dimensional array in C [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
In Python I can define a list, and print it all with one command:
lst = [1,2,3]
print lst
[1,2,3]
Is there any equivalent command in C ? (without using loops), or do I have to print every element by himself?
Thanks!
You can use recursion like in this pseudo code:
void print_array(item array[], size_t len)
{
if (len == 0)
return;
print_item(*array);
print_array(array + 1, len - 1);
}
Modern C compilers can optimize away tail-recursion, so this is likely not much less efficient than a loop.
If it's a string then yes, you can dump the entire contents of the array as long as it's \0 (nul) terminated...fprintf and the likes dump entire arrays all of the time.
char *p;
char string[12] = "A string";
for (p = &string[0]; *p != '\0'; p++)
fprintf(stdout, "%c", *p);
Is akin to
printf("%s", string);

Resources