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;
}
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];