Char string[] Constructor error

hey i have a separte header file with the class:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class image{
  private:
          
    char src;
    point pos;
    scale size;
    
  public: 
          
    image(char * s){
         src = s;
    } 
    
    void render(){
         readimagefile(src, pos.posx, pos.posy, pos.posx+size.width, pos.posy+size.height);
    }
};


and my main.cpp file is :
1
2
3
4
5
6
7
8
9
10
11
#include <graphics.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include "image.h"

int main (){
   initwindow(600,400,"Game"); 
   
   image img("C:/Users/amit/Desktop/game/images/alien.jpg");
...


and when i compile and run on my DE (Dev-C++) i get the following errors:

1
2
3
4
C:\Users\amit\Desktop\game\main.cpp In file included from main.cpp
C:\Users\amit\Desktop\game\image.h In constructor `image::image(char*)':
C:\Users\amit\Desktop\game\image.h invalid conversion from `char*' to `char'
C:\Users\amit\Desktop\game\image.h invalid conversion from `char' to `const char*'    


could someone please explain to me how to pass strings into arrays in c because declaring strings like this - string s = "blahblahblah"; doesn't work for me.

thank you for your time.












src is a char, not a char*.

That's probably what is causing your other error with readimagefile().
excuse me i meant to write is
1
2
3
4
5
6
7
8
9
10
11
    char src[];
    point pos;
    scale size;
    
  public: 
     //point and scale are structures     
    image(char s[],point p, scale z ){
         src = s;
         pos = p;
         size = z;
    } 
It isn't going to work, as src[] isn't initialized in the class, and you cannot initialize objects in a class in the way src needs to be initialized.
There are three ways of doing things:
1. std::string, the most balanced between easy and security
1
2
3
4
5
  std::string src;
public:
  image(const char * s, point p, scale z) {
    src = s;
  }

2. char *, the harder and most balanced between speed and security
1
2
3
4
5
6
7
8
9
10
11
  char * src;
public:
  image(const char * s, point p, scale z){
    unsigned int len = strlen(s);
    src = new char[s+1];
    strcpy(src,s);
  }
  ~image(){
    delete[] src; // You need to delete[] src everytime src is not going to be used anymore
    src = 0;
  }

3. const char *, the easier, but less safer, really not suggesting this way
1
2
3
4
5
  const char * src;
public:
  image(const char * s, point p, scale z){
    src = s;
  }
thanks :)
Happy to be helpful! :D
Topic archived. No new replies allowed.