Reputation: 3143
char *string1;
int i;
string1=(char*)malloc(14*sizeof(char));
for(i=0;i<10;i++)
string1[i]=i+65;
string1[10]=0;
string1[11]=65;
string1[12]=67;
str[13]=0;
printf("%s",string1);
But the output is till the first NUL. Is it possible to print it till the last NUL with out using loop?
Upvotes: 0
Views: 67
Reputation: 754190
You can only write the embedded nulls if you know they're there and you know how long the data is by some means or another. A string is formally defined as a sequence of bytes terminated by a (the first) null byte. What you're seeking to write is not, therefore, a string as defined by the standard. However, assuming a C99 or C11 compiler (so that i
can be declared in the for
loop):
char *string1 = (char *)malloc(14 * sizeof(char));
for (int i = 0; i < 10; i++)
string1[i] = i + 65;
string1[10] = 0;
string1[11] = 65;
string1[12] = 67;
str[13] = 0;
if (fwrite(string1, sizeof(char), 13, stdout) != 13)
…deal with short write (error)…
If you're stuck with a C89 compiler, define int i
outside the loop as you did in the question.
There are those who will excoriate you for including the cast in the call to malloc()
. It isn't necessary in Standard C (and you won't have a pre-standard C compiler unless you're working in an exceptionally unusual environment), but it doesn't do any harm as long as you have your compiler options set so that if you accidentally forget to #include <stdlib.h>
, you will be told about it. That should happen automatically with a C99 or C11 compiler in a standard-conforming mode.
Upvotes: 1