3

I am setting pointers here one to point to name and one to point to name again but get the lenth. How come when i use cout << strlen(tail); it keeps telling me the lenth is 3? Even if i enter something that is 12?

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;

int main()
{
    char name[0];
    cout << "Please enter your name: ";
    cin.getline(name, 256);
    cout << "Your name: " << name << endl;

    char* head = name;
    cout << head[6] << endl;

    char* tail = name;
    cout << strlen(tail);

    return 0;
}
soniccool
  • 5,790
  • 22
  • 60
  • 98

2 Answers2

6

With

char name[0];

You are allocating a buffer of size 0 in which to store data. You need to make it big enough for the longest string you will enter (plus 1 for the NUL terminator), which would be 256 in this case (because you're reading 255 characters and a NUL with cin.get(name, 256)):

char name[256];
Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
  • So its just safer to set it large? – soniccool Dec 16 '11 at 20:35
  • @mystycs no, when you do `char name[0]` you're not giving yourself _any_ memory to use. You need 256 because you do `cin.getline(name, 256)`. If you need less, then change the buffer size _and_ the `cin.getline(name, x)` for `x` to match the buffer size. Also, if you don't know what you're doing, working with C strings can be dangerous (and even if you do it's dangerous sometimes). I would recommend that, **after you are comfortable with pointers and arrays**, use `std::string` for strings and `std::vector` for arrays. – Seth Carnegie Dec 16 '11 at 20:36
  • Well i thought if i set it to 0 it will just expand as someone enters a name or does it not work like that? – soniccool Dec 16 '11 at 20:40
  • 1
    @mystycs no, it will definitely not expand. There is no way you can expand an array after it has been declared (actually you can kinda but don't worry about it). Use `std::string` if you want a buffer that can resize itself. – Seth Carnegie Dec 16 '11 at 20:44
5

Name is declared as zero length. That is going to be a problem.

TJD
  • 11,800
  • 1
  • 26
  • 34