I'm pretty new to the C. I'm trying to create a simple program to represent a point using a structure. It looks like this:
// including standard libraries
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <assert.h>
// including user defined libraries
;
typedef struct point {
char p_name;
double *p_coords;
} point_t;
int main() {
point_t *pt;
pt->p_name = "A";
printf("%c", pt->p_name);
// returning 0 if there are no errors
return 0;
}
The problem is that, when I try to print the name of the point after I assigned the name "A" to it, the program does output nothing except for the exit code, which is (probably) a random number:
Process finished with exit code -1073741819 (0xC0000005)
The fact is that pointers is a concept that is very hard for me to understand (I used to program in python before) and therefore I'm probably missing something. I've also tried out with other variable types such as int, but the result is the same (even the exit status number is the same). Is there a way to fix this behaviour?
P.S.: Excuse my rudimental English, I'm still practising it, and thanks a lot for your time!
you have to use malloc to allocate the memory of the poin_t structure. Something like
point_t *pt = malloc(sizeof(point_t));
pt->p_name = 'A';
printf("%c", pt->p_name);
And very importantly as others mentioned is that pt->p_name = "a"
is also wrong you are allocating int a char
a const char*
I fixed in my example
In your code
pt->p_name = "A";
is wrong for two primary reasons:
pt
point to any valid memory location. Attempt to dereference an invalid memory invokes undefined behavior.p_name
is of type char
. "A"
is a string literal, of type char [x]
, which boils down to char *
for assignment, and they are not compatible types.You need to
pt
points to valid memory location. Actually, you don;t need a pointer here, at all. Define pt
as a variable (not a pointer variable) of the structure type, and access the members via the .
operator.'A'
for assignment, as in character constant, not a string.Pointers must be made to point somewhere. You never assign a value to the pointer pt
, and attempting to dereference an uninitialized pointer value invokes undefined behavior.
You're also assigning a string to a character value. String use double quotes while single characters use single quotes
Use single quotes for a character, and a pointer must first be made to point somewhere:
point_t p;
point_t *pt = &p;
pt->p_name = 'A';
printf("%c", pt->p_name);
User contributions licensed under CC BY-SA 3.0