Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does string + int perform in C?

Tags:

c

string

pointers

I can't figure out this expression:

str + n

where char str[STRING_LENGTH] and int n.

I have worked a lot in Java and was assuming till now that it's concatenation of string and integer, which I doubt now.

What does it mean?

like image 510
Abhishek Avatar asked Oct 09 '13 07:10

Abhishek


People also ask

What does string int do?

int is a primitive variable to store integer numbers. String is an object with methods that allow text manipulation. As others have responded, int is an integer number and string is a text. By adding integers 1 and 2, your result would be 3.

How does string work in C?

In C programming, a string is a sequence of characters terminated with a null character \0 . For example: char c[] = "c string"; When the compiler encounters a sequence of characters enclosed in the double quotation marks, it appends a null character \0 at the end by default.

Can an int be a string in C?

itoa() Function to Convert an Integer to a String in C itoa() is a type casting function in C. This function converts an integer to a null-terminated string.


2 Answers

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.

like image 88
Yu Hao Avatar answered Oct 02 '22 18:10

Yu Hao


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.

like image 20
Bathsheba Avatar answered Oct 02 '22 20:10

Bathsheba