How to iterate over a string in C?

前端 未结 13 1310
花落未央
花落未央 2020-11-28 06:43

Right now I\'m trying this:

#include 

int main(int argc, char *argv[]) {

    if (argc != 3) {

        printf(\"Usage: %s %s sourcecode inpu         


        
13条回答
  •  生来不讨喜
    2020-11-28 07:04

    You want:

    for (i = 0; i < strlen(source); i++){
    

    sizeof gives you the size of the pointer, not the string. However, it would have worked if you had declared the pointer as an array:

    char source[] = "This is an example.";
    

    but if you pass the array to function, that too will decay to a pointer. For strings it's best to always use strlen. And note what others have said about changing printf to use %c. And also, taking mmyers comments on efficiency into account, it would be better to move the call to strlen out of the loop:

    int len = strlen( source );
    for (i = 0; i < len; i++){
    

    or rewrite the loop:

    for (i = 0; source[i] != 0; i++){
    

提交回复
热议问题