What does string + int perform in C?

后端 未结 3 484
栀梦
栀梦 2021-01-05 07:43

I can\'t figure out this expression:

str + n

where char str[STRING_LENGTH] and int n.

I have worked a lot

相关标签:
3条回答
  • 2021-01-05 08:06

    str can be regarded as pointing to the memory address associated with a character sequence of length STRING_LENGTH. As such, c pointer arithmetic is being exploited in your statement str + n. What is is doing is pointing to the memory address of the nth character in the character sequence.

    0 讨论(0)
  • 2021-01-05 08:20

    It's pointer arithmetic. For instance:

    char* str = "hello";
    printf("%s\n", str + 2);
    

    Output: llo. Because str + 2 point to 2 elements after str, thus the first l.

    0 讨论(0)
  • 2021-01-05 08:28

    Yes ans of @Yu Hao and @Bathsheba are correct.
    But if you want to do the concatenation, you can go as following code snippet.

    char string[]="hello";
    int number=4;
    char cated_string[SIZE_CATED_STRING];
    sprintf(cated_string,"%s%d",string,number);
    printf("%s",cated_string);
    

    Happy Coding.

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