0

I am error messages for these lines of code. Im not the best with programming, and can provide more information if need be.

int *linebreak(char *msg, int *breakn){ 
  
    breakn = (int*)count_breaks(msg); //"cast to pointer from integer of different size
    int *arr = (int*)malloc((int)breakn * sizeof(int)); //cast from pointer to integer of different size
Garebears
  • 9
  • 2
  • 2
    `count_breaks` is not disclosed, but the message suggests that the function returns an integer and you are handling that incorrectly. Please post a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) and describe what you want to do. – MikeCAT Feb 05 '21 at 17:18
  • 1
    Have you included `stdlib.h` ? – Eugene Sh. Feb 05 '21 at 17:19
  • 2
    You might mean `*breakn = count_breaks(msg); int *arr = malloc(*breakn * sizeof(int));`? (see also: [c - Do I cast the result of malloc? - Stack Overflow](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc)) – MikeCAT Feb 05 '21 at 17:21
  • 2
    The error for `malloc()` means you did not `#include `. The error for `count_breaks()` means you did not declare it before using it. C99 and later requires functions to be declared (or defined) before being used; only C90 did not mandate that. The error messages are from GCC — you should be using `-std=c18` (or 11 or 99; whatever your compiler supports). GCC 5 upwards defaults to C11; GCC 4 and lower defaults to C90. You should consider using `-Werror -Wall -Wextra` too, so that you don't try running code with compiler-diagnosable bugs in it. – Jonathan Leffler Feb 05 '21 at 17:22
  • That code looks like a REALLY bad idea... – klutt Feb 05 '21 at 17:25
  • [Edit] and show the prototype of `count_breaks`. – Jabberwocky Feb 05 '21 at 17:35

1 Answers1

3

I'm assuming that count_breaks() returns an int and not a pointer to int.
If that's the case, you could try to change your function to

int *linebreak(char *msg, int *breakn)
{
// count_breaks() should return an int
// and it should be assigned to the variable pointed by breakn
    *breakn = count_breaks(msg);

// In C the return value of malloc should not be cast, in C++ is needed though
// You were casting breakn to int, instead of dereferencing it
    int *arr = malloc(*breakn * sizeof(*arr)); 
Jack Lilhammers
  • 1,207
  • 7
  • 19