printing first char

B

Bill Cunningham

I have tried several things and always get a seg fault. What I want to
do is just print out the first char of an array. Here's my latest attempt.
Maybe someone knows what I'm trying to do.

#include <stdio.h>

int main()
{
char a[] = "+hello world\n";
printf("%s\n", a[0]);
return 0;
}
 
L

Lanarcam

Le 22/06/2013 13:09, Bill Cunningham a écrit :
I have tried several things and always get a seg fault. What I want to
do is just print out the first char of an array. Here's my latest attempt.
Maybe someone knows what I'm trying to do.

#include <stdio.h>

int main()
{
char a[] = "+hello world\n";
printf("%s\n", a[0]);
return 0;
}
You should write

printf("%c\n", a[0]);

You want to print a char (%c) not a string (%s).
 
J

Jorgen Grahn

I have tried several things and always get a seg fault. What I want to
do is just print out the first char of an array. Here's my latest attempt.
Maybe someone knows what I'm trying to do.

It's better if you tell us, unless it's a riddle.
#include <stdio.h>

int main()
{
char a[] = "+hello world\n";
printf("%s\n", a[0]);
return 0;
}

You should ask your compiler to report more warnings. Mine tells me:

foo.c:6:5: warning: format '%s' expects argument of type 'char *', but
argument 2 has type 'int'

/Jorgen
 
M

Malcolm McLean

On Sat, 2013-06-22, Bill Cunningham wrote:


foo.c:6:5: warning: format '%s' expects argument of type 'char *', but

argument 2 has type 'int'
What a clever compiler. Mine tells me that printf() is unsafe and tries
to force me to use the wide version, which has no support for floating
point.
 
I

Ian Collins

Malcolm said:
What a clever compiler. Mine tells me that printf() is unsafe and tries
to force me to use the wide version, which has no support for floating
point.

Always have more than one tool in your box!

One of the good features of code derived from OpenSolaris is it has to
compile cleanly with Sun's compiler+lint and gcc.
 
X

Xavier Roche

You might consider minor changes in your code,

Le 23/06/2013 22:23, paskali a écrit :
char *str = "+string+\n";

const char* str = "+string+\n";
(the string is not writable, so this is safer to tell the compiler)
int idx = 0;

size_t idx = 0;
(the canonical integer to be used as offset in memory is size_t)

for(idx = 0 ; str[idx] != '\0' ; idx++) {
(a for-loop is safer is the string is empty, and comparing a character
with the terminating character is better than comparing it with the NULL
pointer)

ie.:
int main(void) {
const char *str = "+string+\n";
size_t idx;

for(idx = 0 ; str[idx] != '\0' ; idx++) {
printf("%c", str[idx]);
}
....
}
 
M

Martin Ambuhl

I have tried several things and always get a seg fault. What I want to
do is just print out the first char of an array. Here's my latest attempt.
Maybe someone knows what I'm trying to do.

Use the correct printf specifier:
#include <stdio.h>

int main()
{
char a[] = "+hello world\n";
printf("%s\n", a[0]); ^
c
return 0;
}
 
B

Barry Schwarz

Bill Cunningham said:
I have tried several things and always get a seg fault. What I want to
do is just print out the first char of an array. Here's my latest attempt.
Maybe someone knows what I'm trying to do.

#include <stdio.h>

int main()
{
char a[] = "+hello world\n";
printf("%s\n", a[0]);
return 0;
}

As well as some one more expert has written you have to replace
printf("%s\n", a[0]) with printf("%c\n", a[0]).

However, some time i have found more confortable to print the entire
string as following:

The original post did not ask about printing anything other than a
single character.
#include <stdio.h>

int main(void) {

char *str = "+string+\n";
int idx = 0;

do {
printf("%c", str[idx++]);
} while(str[idx] != NULL);

This will fail on those systems which define NULL as (void*)0.

Why would you want to call printf multiple times? What is the benefit
since you assume str is a properly terminated string?
 
S

Stephen Sprunk

Usually there are not differents (in bytes) between short and int,
else i would to prefer (and it would to have logically more sense):

unsigned short idx = 0;

There is no guarantee that short and int are the same size, and on most
common systems today they are certainly different (16-bit short, 32-bit
int).

Of course, for this particular program, unsigned (or even signed) char
would work just as well since the string is hardcoded and known to be
rather short.

for(idx = 0 ; str[idx] != '\0' ; idx++) {
(a for-loop is safer is the string is empty, and comparing a
character with the terminating character is better than comparing
it with the NULL pointer)

In this case, for me, there are not differences, of course that you
wrote is good, too!

It's poor practice to test your data for validity _after_ using it. A
while loop is just as simple as a do-while loop, yet it does not suffer
the same defect. I've never found a valid use for do-while loops other
than the macro hack.

Again, in this particular case it doesn't matter since the string is
hardcoded and known to be at least one character long, but defensive
coding is a good habit to practice.

printf("%c", ...) is severe overkill compared to putchar(). True, a
decent compiler may substitute the latter for you when appropriate, but
why write something that is _more_ complicated than required? (Plus,
putchar() is a macro, which implies it'll be faster than printf(),
though the Standard doesn't guarantee that.)

IMHO, while loops are more natural with an iterator, which is the
simpler and more idiomatic construct for sequentially traversing a string:

char *s = str;
while (*s) {
putchar(*s++);
}

but for loops are more natural with indexes:

size_t idx;
for (idx=str; !str[idx]; idx++) {
putchar(str[idx]);
}

That's a matter of style, though; either combination can work.
missing on my code is the *always* present "return 0"

It's implied with C99 and later. In C89, which you seem to be obsessed
with, your code is incorrect without an explicit return.

S
 
S

Stephen Sprunk

GCC has done that for a long time, using clever extensions and a bit of
manipulation of your standard headers. You can even apply the same to
your own functions that use printf()-style format strings, if you're
willing to sacrifice portability (or simplicity, by adding #ifdefs).

How odd; printf() is perfectly safe. I rarely use the wide versions
since I almost always use UTF-8, which was specifically designed to work
(nearly) transparently with non-wide code.

What? Why not?
Always have more than one tool in your box!

One of the good features of code derived from OpenSolaris is it has
to compile cleanly with Sun's compiler+lint and gcc.

Many open-source projects have similar rules (but for GCC only); if not,
patches will usually appear shortly after someone else commits code that
triggers a warning.

Many folks compile with -Werror (or equivalent) by default because
warnings usually indicate bugs. If a warning is spurious, we modify the
code to avoid it rather than turn down the warning level.

S
 
K

Kenny McCormack

There be tolls in these parts.

Ask not for whom the bell tolls...

--
Given Bush and his insanely expensive wars (*), that we will be paying for
for generations to come, the only possible response a sensible person need
ever give, when a GOPer/TeaBagger says anything about "deficits", is a
polite snicker.

(*) Obvious money transfers between the taxpayers and Bush's moneyed
interests. Someday, we'll actually figure out a way to have a war where the
money just gets moved around and nobody (on either side) gets injured or
killed. That will be an accomplishment of which we will be justly proud.
 
K

Keith Thompson

paskali said:
Bill Cunningham said:
I have tried several things and always get a seg fault. What I want to
do is just print out the first char of an array. Here's my latest attempt.
Maybe someone knows what I'm trying to do.

#include <stdio.h>

int main()
{
char a[] = "+hello world\n";
printf("%s\n", a[0]);
return 0;
}

As well as some one more expert has written you have to replace
printf("%s\n", a[0]) with printf("%c\n", a[0]).

However, some time i have found more confortable to print the entire
string as following:

He didn't ask about printing the entire string; he asked about printing
just the first character. Why are you answering a question he didn't
ask?
#include <stdio.h>

int main(void) {

char *str = "+string+\n";
int idx = 0;

do {
printf("%c", str[idx++]);
} while(str[idx] != NULL);

}

May be some one dislike that but for me is good.

NULL is (a macro that expands to) a null *pointer* constant. It doesn't
make much sense to compare a char value to NULL. (It's likely that it
will happen to work, but it's still poor style.) Use '\0' instead.

Using a do-while loop rather than a while loop means you'll always print
at least one character; for an empty string, you'll print the '\0'
character, which is *probably* harmless if you happen to be printing to
a terminal.

If, unlike the OP, you wanted to print an entire string, it would be
silly to use an explicit loop; just call printf with a "%s" format or
use fputs().
 
K

Keith Thompson

Stephen Sprunk said:
GCC has done that for a long time, using clever extensions and a bit of
manipulation of your standard headers. You can even apply the same to
your own functions that use printf()-style format strings, if you're
willing to sacrifice portability (or simplicity, by adding #ifdefs).


How odd; printf() is perfectly safe. I rarely use the wide versions
since I almost always use UTF-8, which was specifically designed to work
(nearly) transparently with non-wide code.

printf() isn't *perfectly* safe; it's very easy to misuse it in ways
that result in undefined behavior. But it's absolutely standard, and
can be used safely if you're careful. I'd be suspicious of any compiler
(*cough* Microsoft) that advised me to use a less portable alternative.
 
J

James Kuyper

On 06/24/2013 11:57 AM, Keith Thompson wrote:
....
printf() isn't *perfectly* safe; it's very easy to misuse it in ways
that result in undefined behavior. But it's absolutely standard, and
can be used safely if you're careful. I'd be suspicious of any compiler
(*cough* Microsoft) that advised me to use a less portable alternative.

My understanding is that printf_s() (K.3.5.3.3), which is new in C2011,
is essentially the same as the "safer" alternative that the Microsoft
compiler wants you to consider. It has certain associated run-time
constraints: the format string must not be null, the %n specifier shall
not appear in the format string, and any argument corresponding to a %s
in the format string shall not be null. If any of these constraints are
violated, printf_s() is guaranteed to return a negative number, which
appears to be the sense in which it is considered to be safer.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,054
Latest member
LucyCarper

Latest Threads

Top