Can a pointer to a string be used in a printf?

前端 未结 4 536
梦谈多话
梦谈多话 2021-01-31 10:23

I am thinking of something like:

#include 
#include 
#include 

int main(void) {
    //test pointer to string
    c         


        
相关标签:
4条回答
  • 2021-01-31 11:02
    printf("%s\n", ptr);
    

    Is this what you want?

    By the way, from printf(3), here's the documentation for the s conversion specifier (i.e %s):

    If no l modifier is present: The const char * argument is expected to be a pointer to an array of character type (pointer to a string). Characters from the array are written up to (but not including) a terminating null byte ('\0'); if a precision is specified, no more than the number specified are written. If a precision is given, no null byte need be present; if the precision is not specified, or is greater than the size of the array, the array must contain a terminating null byte.

    0 讨论(0)
  • 2021-01-31 11:07

    The "%s" format specifier for printf always expects a char* argument.

    Given:

    char s[] = "hello";
    char *p = "world";
    printf("%s, %s\n", s, p);
    

    it looks like you're passing an array for the first %s and a pointer for the second, but in fact you're (correctly) passing pointers for both.

    In C, any expression of array type is implicitly converted to a pointer to the array's first element unless it's in one of the following three contexts:

    • It's an argument to the unary "&" (address-of) operator
    • It's an argument to the unary "sizeof" operator
    • It's a string literal in an initializer used to initialize an array object.

    (I think C++ has one or two other exceptions.)

    The implementation of printf() sees the "%s", assumes that the corresponding argument is a pointer to char, and uses that pointer to traverse the string and print it.

    Section 6 of the comp.lang.c FAQ has an excellent discussion of this.

    0 讨论(0)
  • 2021-01-31 11:08

    you should do "printf("S: %s\nPTR: %s\n", s, ptr); " instead of printf("S: %s\nPTR: %s\n", s, *ptr);

    difference between ptr and *ptr is: ptr gives you the address in the memory of the variable you are pointing to and *ptr gives rather the value of the pointed variable In this case is *ptr = ptr[0]

    this code will show what i mean:

    printf("\tS: %s\n\tPTR: %s\n\tAddress of the pointed Value: %x\n\tValue of the whole String: %s\n\tValue of the first character of the String: %c\n", s, ptr,ptr,ptr,*ptr);
    
    0 讨论(0)
  • 2021-01-31 11:15

    In my experience you should get segmentation fault when you try to use %s directive with *p.

    0 讨论(0)
提交回复
热议问题