0

I'm trying to use strcpy in order to put a string in an array of strings. This is my definiton of the arrays:

char movies[10][150], movie[150];
int i = 0, j = 0;

currentChar = getchar();

while(currentChar != EOF)
{
    while(currentChar!='\n')
    {
        movie[i] = currentChar;
        currentChar = getchar();
        i++;
    }

    strcpy(*(movies + j*10*15), (char*)movie);
    j++;
    currentChar = getchar();
}

Trying to debug it in c++ console, I get a 'Buffer is too small' message.

note: My input is "Django unshaved:a bit bloody, but overall a solid film" which does not exceed the 150 chars.

thanks for helping.

edit: code edited to show full picture

  • Destination should be `*(movies + j)`? – Montaldo Jun 02 '14 at 09:36
  • hi, i should mention that the strcpy is in a while loop which should put the string in movies[j][0] – user3698757 Jun 02 '14 at 09:38
  • @user3698757 If there is relevant code which is not shown, please edit the question and add it. – user694733 Jun 02 '14 at 09:40
  • Yeah, but `movies[j][0]` is only a single character. You want `movies[j]`, which is a buffer of 150 chars. The first index points to your string/film title in the string array, the second index points to characters in that string. (If it isn't beyond the terminating null, that is.) – M Oehm Jun 02 '14 at 09:40

3 Answers3

3

You should use this code instead:

strcpy(movies[j], movie);

IMHO, it doesn't make sense to define a two-dimensional array and then use it as if it was one large one-dimensional array defined as char[1500].

Also, which compiler are you using that generates such a message for C-code?

scc
  • 10,342
  • 10
  • 51
  • 65
Axel
  • 13,939
  • 5
  • 50
  • 79
  • This is much less error prone than doing naked pointer arithmetic, and easier to read. Furthermore if the storage of strings is altered, perhaps to save space or remove the 149 length limit, only the movies declaration would need to change, not this code. – Rob11311 Jun 02 '14 at 09:42
0

Your copy function call should be:

strcpy((movies + j*150), (char*)movie);
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Sami
  • 155
  • 3
0

Finally I solved the problem. Apparently, in the end of 'movie' there wasn't a '\n' character and strcpy could not handle it.

Adding a '\n' at the end of the string solves the problem.