Reputation: 25
I'm creating a simple program to see how a string populates an array.
#include <stdio.h>
#include <string.h>
#include <stddef.h>
#include <stdlib.h>
int main(void)
{
char string1[100];
int i;
printf("Enter sentence.\n");
fgets(string1, 100, stdin);
for (i=0; i<=15; i++)
puts(&string1[i]);
return 0;
}
I'm having a bit of a problem understanding how the string is populating an array. My expectation is that the string will be completely stored in string1[0] and any further indexes will come up blank. However, when I throw the loop to see if my assumption is true, it turns out that every index has been filled in by the string. Am I misunderstanding how the string is filling the array?
Upvotes: 1
Views: 71
Reputation: 2259
string is not stored in string1[0] but string's first character is stored at string1[0]
or string starts at (string1+0)
. Here, &string1[0] or (string1+0)
can be seen as a pointer, a pointer to C String string1
.
In that sense, every valid index i
of string1
will give you a valid pointer (string1 + i)
which will point to some part of C String string1
.
In the last for loop you are printing the suffixes of string string1
which are pointed by (string1 + 0), (string1 + 1), (string1 + 2)
...
Upvotes: 1
Reputation: 11514
Your problem is not string1
layout per se but how puts
interprets it. Strings are represented by char
arrays in C while their end is marked as null terminator (character with code 0):
S e n t e n c e \0
^ ^
string1 &string1[5]
&string1[5]
is a pointer to a one character, but since the following character is not null terminator, following memory is interpreted as a string and nce
gets printed.
You'll need to use putc
and access individual characters:
putc(string1[i])
Upvotes: 1
Reputation: 170202
For the string "Hello!", the memory representation would be something like this
+-------+-------+-------+-------+-------+-------+-------+
| 'H' | 'e' | 'l' | 'l' | 'o' | '!' | '\0' |
+-------+-------+-------+-------+-------+-------+-------+
The first cell, at index 0, contains the first character. And each subsequent character is contained in a cell with an increasing index.
Library functions like puts
expect you to pass the address of the first character, and then they read the string up to \0
.
So if you pass simply string1
or &string1[0]
, it will resolve to the address of 'H'
.
If you pass &string[1]
, it will resolve to the address of 'e'
, and the library function will think that is the first character, because that's the contract C strings are designed with.
Upvotes: 2