Given a string char *s:
How do you print it the string to the terminal one character at a time.
Your help is greatly appreciated.
Given a string char *s:
How do you print it the string to the terminal one character at a time.
Your help is greatly appreciated.
well, I don't do much single char putting but you could do:
for(i = 0; i < strlen(string); i++)
printf("%c", string[i]);
//or...
putchar(string[i]);
..or something to that effect.
or,
while(*string)
putchar(*string++);
Yes, just increment the pointer to point to the next char and output that char. Understand? Need code?
1978 Silver Anniversary Corvette
Yes, you must point to something!
1978 Silver Anniversary Corvette
Not necessarily. It only might crash if you try to alter the contents of a literal, which is not happening here. I wouldn't bother allocating space for a string on the heap before doing anything with it, unless it's length (or existence) isn't known until runtime. Either use the stack or a literal.Originally posted by vVv
Would crash otherwise.
Sorensen, I beg to differ. I always thought that if you try to view/change unallocated memory (unnamed memory) that it is illegal at that point...You can go no further...Originally posted by Sorensen
Not necessarily. It only might crash if you try to alter the contents of a literal, which is not happening here. I wouldn't bother allocating space for a string on the heap before doing anything with it, unless it's length (or existence) isn't known until runtime. Either use the stack or a literal.
Garfield
1978 Silver Anniversary Corvette
What unallocated memory? If it's a dangling pointer then this is true, but something like Sebastiani's code would work for -
char * x = "literal string";
char y[] = "stack string";
So there is no need to manually allocate memory, other than for the reasons I stated originally.
>> char * x = "literal string"; <<
This would be allocating the memory at declaration time...
1978 Silver Anniversary Corvette
>This would be allocating the memory at declaration time...
Erm.. no it wouldn't. It's taking a pointer and initialising it with the address of a string literal, which already resides in memory. Check the address of the string, it won't be on the stack or the heap, but in one of the data segments.
Okay, I see...Originally posted by Sorensen
>This would be allocating the memory at declaration time...
Erm.. no it wouldn't. It's taking a pointer and initialising it with the address of a string literal, which already resides in memory. Check the address of the string, it won't be on the stack or the heap, but in one of the data segments.
Garfield
1978 Silver Anniversary Corvette