Here is a tid-bit of code i found.
/* Allocate space for a string dynamically, request user input, and then print the string backwards. */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void main(void)
{
char *s;
register int t;
s = malloc(80);
if(!s) {
printf("Memory request failed.\n");
exit(1);
}
fget(s);
for(t=strlen(s)-1; t>=0; t--) putchar(s[t]);
free(s);
}
Quote from: MrRaza on April 22, 2003, 08:01 AM
Here is a tid-bit of code i found.
/* Allocate space for a string dynamically, request user input, and then print the string backwards. */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void main(void)
{
char *s;
register int t;
s = malloc(80)
if(!s) {
printf("Memory request failed.\n");
exit(1);
}
get(s);
for(t=strlen(s)-1; t>=0; t--+) putchar(s[t]);
free(s)
}
That's got quite a few errors:
t--+? No semicolon after
free(s) or
malloc(80)?
get instead of
fgets (using
gets is a open invitation for buffer overflows)?
void main?
Suggestion: You might check that examples you post are valid code and emphasize good programming practices.
i had it in my notes, i must of had some typo's, sorry about that...
btw, i forget what the standard is for the void main() function...
And you still get the point of what the example was trying to show. Besides a minor amount of errors on my part, it was a good example.
Even if you fixed sky's errors, that still wouldn't compile because malloc returns a void* pointer, not a char*. This would be better:
s = (char*)malloc(80);
But that is still bad practice, this would actually be best:
s = (char*)malloc(sizeof(char) * 80);
And don't worry about that taking longer to run, because it won't, the compiler will hardcode in the result of that multiplication for you.
that may be the case, "sizeof(char)*80" is still silly though :P
might as well use
s = (T_CHAR*)malloc(sizeof(T_CHAR)*80);
if you're going to do all that.
register int? What a rare beast.
Nowadays, register is pretty much deprecated. Modern compilers will be able to optimize your C/C++ code much better than you will, these dinky little hints now serve no purpose. Optimizers know much more about generated code, so let them choose what would be best served as a register variable.
Not to mention accessing a word (or byte, dword, qword, whatever) on the stack, which probably spends more time in your CPU's cache than in the RAM, is almost as fast as accessing a register, especially with modern CPUs.
Quote from: Arta[vL] on April 22, 2003, 12:49 PM
that may be the case, "sizeof(char)*80" is still silly though :P
It's true, but I like doing that anyway, just in case I later change it to an int or something silly like that :P
doing that ensures portability
Is there unicode C?
Erm... Yes, ANSI C supports wide strings natively.