0

This code keep saying : error: invalid initializer

char * ss = "hello world";
char s[10] = ss;
std::transform(s, s + std::strlen(s), s, static_cast<int(*)(int)>(std::toupper));

How can it be fixed?

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
John
  • 107
  • 1
  • 4
  • 11

4 Answers4

2

Your initializer of the array with a C string is invalid. The good news is that you do not need it at all:

char * ss = "hello world";
char s[12];
std::transform(ss, ss + std::strlen(ss)+1, s, static_cast<int(*)(int)>(std::toupper));
cerr << s << endl;

Note that I padded your s array with an extra element for the terminating zero.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • @SethCarnegie You are correct - I just fixed it half a minute ago. My counting is a bit rusty this morning (not surprising, given it's the first day of the new year :) – Sergey Kalinichenko Jan 01 '12 at 16:55
1
char s[10] = ss;

This tries to set an array's value equal to a pointer, which doesn't make any sense. Also, ten bytes isn't enough (there's a terminating zero byte on the end of a C-style string). Try:

char s[20];
strcpy(s, ss);
David Schwartz
  • 179,497
  • 17
  • 214
  • 278
0

You can't assign a pointer to an array because you can't assign anything to arrays but initialiser lists. You need to copy the characters from ss to s. Also, an array of size 10 is too small to hold "hello world". Example:

char * ss = "hello world";
char s[12] = {}; // fill s with 0s

strncpy(s, ss, 11); // copy characters from ss to s

Alternatively, you could do

char s[] = "hello world"; // create an array on the stack, and fill it with
                          // "hello world". Note that we left out the size because
                          // the compiler can tell how big to make it

                          // this also lets us operate on the array instead of
                          // having to make a copy

std::transform(s, s + sizeof(s) - 1, s, static_cast<int(*)(int)>(std::toupper));
Seth Carnegie
  • 73,875
  • 22
  • 181
  • 249
0

Your array assignment is illegal and, in the case of your code, isn't needed in the first place.

const char * ss = "hello world";
char s[12];
std::transform(ss, ss + std::strlen(ss)+1, s, static_cast<int(*)(int)>(std::toupper));
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180