0

I have done a class who contains itself a array of an other class. When I edit one member of this other class and want to print it, it print something not interpretable.

There is the class in file.hpp:

class channel
{
        char name[50];

     public:
        channel();
        void setName(char*);
        char *getName();
}

class Case
{
        char name[50];
        channel *channels;

    public:
        Case();
        channel get_channel(int);
}

and there is the file.cpp:

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include "file.hpp"

channel::channel(){}

void channel::setName(char *c)
{
    char buffer[50];

    sprintf(buffer, "%s", c);

    sprintf(name, "%s", buffer);
}

char* channel::getName()
{
    return nom;
}


Case::Case()
{
    int i;

    channels = (channel *)malloc(14 * sizeof(channel));

    for (i = 0; i < 14; i++)
    {
        channels[i] = channel();
    }
}

channel Case::get_channel(int nb)
{
    return channels[nb];
}


void main()
{
    Case b1 = Case();
    b1.get_channel(4).setName("food");
    printf("%s", b1.get_channel(4).getName());
}

So I already tried to modify the way to modify the member name with strcpy() or sprintf() and none of this worked.

I also tried to allocate statically like this in file.hpp: Channel Channels[14]

and dynamically like above but it didn't resolved the problem.

Nemul
  • 15
  • 4
  • 5
    Function `channel Case::get_channel(int nb)` returns a copy of `channel`, so `.setName("food")` changes this copy, while the object inside `b1` is left intact. Then when you print you print emptiness, because you didn't change the object – Alexey S. Larionov Mar 01 '23 at 10:27
  • 1
    Return `channel&` from `Case::get_channel` instead, or a pointer/smart pointer – Alexey S. Larionov Mar 01 '23 at 10:28
  • You problem is with `get_channel`, not with initialization. But your entire code looks like C with classes rather than C++, may I suggest getting [a good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/) to learn from? – Yksisarvinen Mar 01 '23 at 10:28
  • 1
    either there are some requirements you missed to tell us or you need to get rid of `malloc` and raw pointers and character arrays. Use `std::string` – 463035818_is_not_an_ai Mar 01 '23 at 10:31
  • @Yksisarvinen is right. You are making life difficult ofr yourself. Use Flowers book for Engineers and implement the complex class and then you will find this problem easy to implement. Also, I've not done it, but people are moving to Rust now. – Eamonn Kenny Mar 01 '23 at 10:55

1 Answers1

0

The culprit:

channel Case::get_channel(int);

This returns a copy of a channel, so the actual channel owned by b1 isn't modified. What you need is to return a reference.

channel& Case::get_channel(int nb)
{
    return channels[nb];
}
guard3
  • 823
  • 4
  • 13