-3

I am trying to create a pointer to a char and pass it to function as a char*. here is my code to define the char array
it seems the compiler does not recognize the end of the string because the function display does not show a correct string

char myword[] = { 'H', 'e', 'l', 'l', 'o', '\0' }; 
char  str[] = {'M','i','k','e',' ','s','m','i','t','h','\0'};
char str2[] = "Dragic\0";
char* pname=&str[0];
char* pteam=&str2[0];
Display(myword);
DeveloperLife
  • 21
  • 2
  • 5

2 Answers2

1

You have error inside your Display() function. Code you posted is perfectly valid. You can check it here.

Anyway, why do you declare these arrays this way? You can simply do:

char myword[] = "Hello";
char str[] = "Mike Smith";
char str2[] = "Dragic";

char* pname = &str[0];
char* pteam = &str2[0];

In case of constant string literals, null terminator is appended automatically. Then:

printf("%s\n", myword);
printf("%s\n", str);
printf("%s\n", str2);
printf("%s\n", pname);
printf("%s\n", pteam);

Output:

Hello
Mike Smith
Dragic
Mike Smith
Dragic

You can find working sample here.

Mateusz Grzejek
  • 11,698
  • 3
  • 32
  • 49
-1

Do not use char arrays if you just need a string, use std::string. If you need an array, use std::vector or std::array

If you really really have to use naked arrays(heap allocated) and pointers, at least encapsulate it with RAII.

Community
  • 1
  • 1
bmeric
  • 1,124
  • 1
  • 17
  • 27
  • In case of fixed arrays, created as objects on local stack I see no point in using `RAII`. There is nothing here, that can lead to memory leak of any kind. – Mateusz Grzejek May 04 '15 at 10:10