Having trouble with char pointers - c

I'm having trouble with char pointers. I'm trying to get the value from the store_stuff function and print it into the main function. How can I do this?
#include <stdio.h>
#include <string.h>
#include <assert.h>
void store_stuff(char *name, int *age);
int main(void) {
char *name;
int age;
store_stuff(&name, &age); // I'm having trouble here
printf("Name: %s\n", name);
printf("Age: %d\n", age);
}
void store_stuff(char **name, int *age) {
*name = "John";
*age = 31;
}

https://ideone.com/5HOPGQ
#include <stdio.h>
#include <string.h>
#include <assert.h>
char *store_stuff(char **name, int *age);
int main(void) {
char *name;
int age;
store_stuff(&name, &age); // I'm having trouble here
printf("Name: %s\n", name);
printf("Age: %d\n", age);
}
char *store_stuff(char **name, int *age) {
*name = "John";
*age = 31;
return *name;
}

Make it
void store_stuff(char** name, int* age)
{
*name = "John";
*age = 31;
}
You need that pointer to a pointer for name assignment to make its way out of store_stuff
Also you need to change your definition of
char name
to
char* name
Since name itself wants to be a pointer to interact as a string
EDIT: And of course, be sure to make your prototype consistent at the top with void store_stuff(char** name, int* age);

Related

Why does my char array not print anything?

In c I am trying to assign a char array inside a struct with a user provided value, here is my code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct person
{
char name[20];
int age;
};
struct person *assign(char arr[], int age)
{
struct person *x = malloc(sizeof(struct person));
x->name[20] = arr[20];
x->age = 21;
return x;
}
int main()
{
char name[20] = "Arthur morgan";
int age = 34;
struct person* person1 = assign(name, age);
printf("name: %s\n", person1->name);
printf("age: %d\n", person1->age);
return 0;
}
The problem is that the name prints nothing for some reason, the age however prints as expected.
Why is the name not printing correctly?
x->name[20] = arr[20];
It does not copy the array
It copies 1 character and you are accessing array outside its bounds which is undefined behaviour (UB)
It is better to use objects not types in sizeof
Always check the result of malloc
You need to copy the string using strcpy function
struct person *assign(char arr[], int age)
{
struct person *x = malloc(sizeof(*x));
if(x)
{
strcpy(x->name,arr);
x->age = 21;
}
return x;
}
https://godbolt.org/z/vKddb4b9a

initialise constructor values of structure using pointer in c [duplicate]

This question already has answers here:
How do malloc() and free() work?
(13 answers)
Closed 3 years ago.
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
struct Person {
char name[50];
int year_of_birth;
char sex[7];
char father[50];
char mother[50];
char significant_other[50];
char children[50];
};
struct Person* person_constructor(char *name, int year_of_birth, char *sex);
int main(){
struct Person* p1 = person_constructor("Abbas", 1970, "male");
}
struct Person* person_constructor(char *name, int year_of_birth, char *sex) {
struct Person *p;
printf("%s",*name);
printf("%s",*sex);
printf("%d",&year_of_birth);
// how to initalise these here and return name, age and sex everytime , can you tell me in print function
}
i want to do :
Person* person_constructor(char *name, int year_of_birth, char *sex);
A person with the given arguments and return it.
Also allocate memory.
In example code bellow you can find one of possible solutions to your question.
In C language is not possible to return more then one variable, but you can return pointer to constructed structure object and access structure members using notation stuct_ptr->struct_member.
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
struct Person {
char name[50];
int year_of_birth;
char sex[7];
char father[50];
char mother[50];
char significant_other[50];
char children[50];
};
struct Person* person_constructor(char *name, int year_of_birth, char *sex);
int main(){
struct Person* p1 = person_constructor("Abbas", 1970, "male");
/* it is not possible to return more variables in C */
/* you can use pointer to access members from constructed structure: */
printf("print from main:\n %s %d %s \n", p1->name, p1->year_of_birth, p1->sex);
if( p1 != NULL) free(p1); /* do not forget do deallocate something taht is allocated */
return 0;
}
struct Person* person_constructor(char *name, int year_of_birth, char *sex) {
struct Person *p = calloc(1, sizeof(struct Person));
if( p == NULL ) return p; /* memory alocation failed! */
strcpy(p->name, name);
p->year_of_birth = year_of_birth;
strcpy(p->sex, sex);
printf("print from constructor:\n");
printf("%s ",p->name);
printf("%s ",p->sex);
printf("%d \n",p->year_of_birth);
return p;
}

Struct not retaining data when passed as a pointer

I've defined a header file with a struct and function prototypes that take a pointer to a struct as a parameter. The code compilation goes fine except that struct instantiated in the main do not seem to retain numerical data.
This is the header file:
#ifndef _GETDATA
#define _GETDATA
#include <stdio.h>
struct PERSONDATA{
char name[20];
double age,mass;
};
typedef struct PERSONDATA person;
extern void getData(person *);
extern void getName(char *,int);
#endif
This is the getData.c file:
#include <stdio.h>
#include "GETDATA.h"
void getData(person *ptr)
{
printf("Enter name: ");
getName(ptr->name,sizeof(ptr->name));
printf("enter age: ");
scanf("%f",&(ptr->age));
printf("enter mass: ");
scanf("%f",&(ptr->mass));
}
and this is the getName.c file:
#include <stdio.h>
#include "GETDATA.h"
void getName(char *ptrName, int varSize)
{
int i=0;
do
{
*(ptrName++) = getchar();
++i;
if(i==varSize) printf("array full, EXITING!\n");
}while(*(ptrName-1)!='\n' && i<varSize);
*(ptrName-1) = '\0';
}
The main function is as follows:
#include <stdio.h>
#include "GETDATA.h"
int main(int argc, char **argv)
{
person human1;
printf("hello, world!\n\n");
getData(&human1);
printf("\nData entered: \n");
printf("\tname = %s\n",human1.name);
printf("\tMass = %f\n",&(human1.mass));
printf("\tAge = %f\n",&(human1.age));
return 0;
}
This is the console output when the code is run:
What could be going wrong here?
Your values are doubles, not floats. You need to use %lf with scanf():
printf("enter age: ");
scanf("%lf",&(ptr->age));
printf("enter mass: ");
scanf("%lf",&(ptr->mass));
Also, your prints are wrong. You are passing a pointer. It should be
printf("\tMass = %f\n",human1.mass);
printf("\tAge = %f\n",human1.age);

C programming - why garbage data inside my struct?

I have the following program in C:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
typedef struct str{
char * s;
int len;
}string;
typedef struct stud{
unsigned int id;
string name;
char gender;
}student;
student* addstud(const int id, const char name[64], const char gender);
student* addstud(void){
char buf[64];
struct stud *sb;
sb = (struct stud*)malloc(sizeof(struct stud));
printf("Enter student ID:\n");
scanf("%d",&sb->id);
printf("Enter student name:\n");
scanf("%s", buf);
sb->name.s = buf;
sb->name.len = (int)strlen(buf);
printf("Enter student gender:\n");
scanf(" %c", &sb->gender);
printf("Student ID: %d, name: %s, gender: %c\n", sb->id, sb->name.s, sb->gender);
return sb;
}
int main(){
student *mystudent;
mystudent=addstud();
printf("Student ID: %d, name: %s, gender: %c\n", mystudent->id, mystudent->name.s, mystudent->gender);
getchar();
return 0;
}
In the addstud() function, everthing is fine but in main() when I try to print out the student name from mystudent->name.s it just garbage data. I don't understand why this could happened as it was clearly fine in addstud() function and both pointers point to the same memory address :( Could anyone please shred some light what I did wrong here, please? Thank you!
you can duplicate the buf.
sb->name.s = strdup(buf);
char buf[64];
Here buf is local to function addstud() so once you exit the function this array is out of scope and accessing it will lead to undefined behavior.
sb->name.s = buf;
In this, buf is a local variable to the function addstud(). So, when the function exits, accessing the variable is UB.
You have 2 options,
1)Either allot memory for buf using malloc()
2) Use strcpy() to copy the contents of the variable buf to sb->name.s

displaying values in c structure array

I'm trying to display the values of my structure array, the compiler throws out the following error:
athletes.c:17: error: expected ')' before '*' token
Could someone help me out with a solution and if possible an explanation as to what I did wrong.
#include <stdio.h>
#include <string.h>
struct athlete {
char last_name[25];
char first_name [20];
int rank;
float salary;
};
int main (void) {
struct athlete players[] = {{"Lebron", "James",1,25}, {"Durant", "Kevin",3,20},{"Duncan","Tim",2,12}};
display_jock(players);
}
void display_jock(athlete *p) {
printf ("%10c%10c%10d%10.1f \n", p[0].last_name,p[0].first_name,p[0].rank, p[0].salary);
printf ("%10c%10c%10d%10.1f \n", p[1].last_name,p[1].first_name,p[1].rank, p[1].salary);
printf ("%10c%10c%10d%10.1f \n", p[2].last_name,p[2].first_name,p[2].rank, p[2].salary);
}
there are several small errors:
your code does not know the type "athlete", so your class display_jock should be defined with argument struct athlete: void display_jock(struct athlete *p)
you should forward declare that function: otherwise main doesn't know it (edit:you could also just move the display_jock function at the top of the main function)
when printing a char array, you should use %s instead of %c when using printf.
your main function should return an int (since it is declared as int main...)
this is your code fixed up:
#include <stdio.h>
#include <string.h>
struct athlete {
char last_name[25];
char first_name [20];
int rank;
float salary;
};
void display_jock(struct athlete *p);
int main (void) {
struct athlete players[] = {{"Lebron", "James",1,25}, {"Durant", "Kevin",3,20},{"Duncan","Tim",2,12}};
display_jock(players);
return 0;
}
void display_jock(struct athlete *p) {
printf ("%s%s%10d%10.1f \n", p[0].last_name,p[0].first_name,p[0].rank, p[0].salary);
printf ("%s%s%10d%10.1f \n", p[1].last_name,p[1].first_name,p[1].rank, p[1].salary);
printf ("%s%s%10d%10.1f \n", p[2].last_name,p[2].first_name,p[2].rank, p[2].salary);
}

Resources