ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
You can compile that with gcc? How do you do that?! Actually this is not C, but C++, so you should compile with g++. Hmmm..., however you have to allocate memory for 'foo.m' using the 'new' keyword. Otherwise you'll run into a segfault.
#include <iostream>
using namespace std;
struct charptr {
char* m;
};
int main() {
charptr foo; //maybe this should be struct charptr foo;
*(foo.m) = 'c';
cout << (*(foo.m)) << '\n';
}
Not sure if C++ uses struct the same way C does but if it does im suprized this even compiles.
in C it would look something like this
Code:
#include<stdio.h>
struct charptr {
char *m;
}
int main ()
{
struct charptr foo; // creates the pointer but it points to nothing
char letter; //Creates a place in memory to store the data
letter = 'c'; //assiens the data to the address space
foo.m = &letter; // points the pointer to the address in
// memory that contains the data.
printf("%c\n",*foo.m); //derefrence the pointer to get the data
return 0;
}
Just follow Fleysm's advice. You didn't allocate any memory there for it. You'll get unpredictable results without allocating memory properly. As far as "gcc" or "g++," its the same thing. The real issue is the extension of the filename, compiling a .c with g++, invokes the C compiler, compiling a .cpp with gcc invokes the C++ compiler.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.