Using %s in C correctly - very basic level

后端 未结 5 958
庸人自扰
庸人自扰 2020-12-10 05:09

I know that %s is a string of characters, but I don\'t know how to use it. Can anyone provide me a very basic example of how its used and how its different from char ?

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-10 05:29

    %s is the representation of an array of char

    char string[10] // here is a array of chars, they max length is 10;
    char character; // just a char 1 letter/from the ascii map
    
    character = 'a'; // assign 'a' to character
    printf("character %c  ",a); //we will display 'a' to stout
    

    so string is an array of char we can assign multiple character per space of memory

    string[0]='h';
    string[1]='e';
    string[2]='l';
    string[3]='l';
    string[4]='o';
    string[5]=(char) 0;//asigning the last element of the 'word' a mark so the string ends
    

    this assignation can be done at initialization like char word="this is a word" // the word array of chars got this string now and is statically defined

    toy can also assign values to the array of chars assigning it with functions like strcpy;

    strcpy(string,"hello" );
    

    this do the same as the example and automatically add the (char) 0 at the end

    so if you print it with %S printf("my string %s",string);

    and how string is a array we can just display part of it

    //                         the array    one char
    printf("first letter of wrd %s     is    :%c ",string,string[1]  );
    

提交回复
热议问题