Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing a Char *

Tags:

c

char

printf

I apologize in advance for the dumb question!

Here is my struct def:

struct vcard {
  char *cnet;
  char *email;
  char *fname;
  char *lname;
  char *tel;
};

I am trying to print a representation of this struct with the function vcard_show(vcard *c), but the compiler is throwing back an warning:

void vcard_show(struct vcard *c)
{
    printf("First Name: %c\n", c->fname);
    printf("Last Name: %c\n", c->lname);
    printf("CNet ID: %c\n", c->cnet);
    printf("Email: %c\n", c->email);
    printf("Phone Number: %c\n", c->tel);
}

When compiled: "warning: format ‘%c’ expects type ‘int’, but argument 2 has type ‘char *’"

Isn't %c the symbol for char*?

like image 639
Alex Nichols Avatar asked Mar 08 '13 00:03

Alex Nichols


People also ask

What does char * mean in C?

In C, char* means a pointer to a character. Strings are an array of characters eliminated by the null character in C.

Can you print a char?

yes, %c will print a single char: printf("%c", 'h'); also, putchar / putc will work too.

How do you print a char function?

using printf() If we want to do a string output in C stored in memory and we want to output it as it is, then we can use the printf() function. This function, like scanf() uses the access specifier %s to output strings. The complete syntax for this method is: printf("%s", char *s);

Is char * a pointer or a string?

You're working with pointers. var1 is a char pointer ( const char* ). It is not a string.


2 Answers

You want to use %s, which is for strings (char*). %c is for single characters (char).

An asterisk * after a type makes it a pointer to type. So char* is actually a pointer to a character. In C, strings are passed-by-reference by passing the pointer to the first character of the string. The end of the string is determined by setting the byte after the last character of the string to NULL (0).

like image 184
Jonathon Simister Avatar answered Oct 17 '22 11:10

Jonathon Simister


The property type encoding for a char * is %s. %c is for a char (not the pointer just a single char)

like image 5
DanZimm Avatar answered Oct 17 '22 09:10

DanZimm