tags:

views:

193

answers:

4

I am trying to make a function in C that will print a string taken as a parameter. Is this even possible in C?

I have something like this in my header file, but string is not a valid identifier. I understand there are no strings in C, but what's the string.h class for?

#include <string.h>    

#ifndef _NEWMAIN_H
#define _NEWMAIN_H

#ifdef __cplusplus
extern "C" {
#endif

    void print (string message){  //this is where i need help
        printf("%s", message);
    }


#ifdef __cplusplus
}
#endif

#endif /* _NEWMAIN_H */
+3  A: 
void print (const char* message) {
            printf("%s", message);
}
Karl Voigtland
+4  A: 

In C, there is no native string type.

C handles strings as a null-terminated char array.

For example:

char* string = "this is a string";

The string.h exists to perform string manipulation functions on C strings, which are of type char*.

When printing a string using printf, one would pass in a variable of char*:

char* string_to_print = "Hello";
printf("%s", string_to_print);

For more information on strings in C, the Wikipedia page on C strings would be a good start.

coobird
I think most C compilers let you get away with non-const pointers to string literals, but "this is a string" really is const and should be pointed at by a const char *.
Zan Lynx
A: 

There are no strings in C, since there are no classes in C. string.h provides the routines for handling string text manipulation in C, using pointers to char.

You'll want to rewrite this like:

void print(const char* message) {
    printf(message); // You don't need the formatting, since you're only passing through the string
}

That being said, it's not really any different than just calling printf directly.

Reed Copsey
You should always use formating even if its just "%s". If the string you are printing is "%s" you've got a problem.
Craig
@Craig Only if you print strings from unreliable source (such as user or external), however printing your own strings without format is safe. Dogmas are bad - you need to know WHY.
qrdl
+1  A: 

After thinking about it briefly, for your homework assignment, which is to replace printf, you will want to use char * as pointed out by others, and use fwrite to stdout.

For a related question you can look at http://stackoverflow.com/questions/528559/c-c-best-way-to-send-a-number-of-bytes-to-stdout

James Black