473,386 Members | 1,668 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

How to use dinamic struct

what's wrong this code ?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

typedef struct{
char *name;
int no;

}Person;

int main()
{
Person *s = NULL;

s = (Person *)malloc(sizeof(Person));

printf("name: ");
scanf("%s", &s->name);
printf("number: ");
scanf("%d", &s->no);

printf("Name: %s Number: %d", s->name, s->no);

free(s);

system("pause");

return 0;
}
Dec 18 '07 #1
6 1428
In article <e3**********************************@i29g2000prf. googlegroups.com>,
berte <be********@gmail.comwrote:
>what's wrong this code ?
A number of things, but the one that is probably causing you
the most grief is that when you malloc memory for the structure
s, you get -space- for the character pointer s->name, but
you do not allocate any space for the string pointed to. When you
then try to scanf into &s->name you are trying to write the
string contents into the character pointer space.

There are a number of other points of bad style, lax checking,
and even a bit more undefined behaviour lurking in your code,
but the above is the problem most likely to lead to outright
crashes.

>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

typedef struct{
char *name;
int no;

}Person;

int main()
{
Person *s = NULL;

s = (Person *)malloc(sizeof(Person));

printf("name: ");
scanf("%s", &s->name);
printf("number: ");
scanf("%d", &s->no);

printf("Name: %s Number: %d", s->name, s->no);

free(s);

system("pause");

return 0;
}

--
"I will speculate that [...] applications [...] could actually see a
performance boost for most users by going dual-core [...] because it
is running the adware and spyware that [...] are otherwise slowing
down the single CPU that user has today" -- Herb Sutter
Dec 18 '07 #2
In article <e3**********************************@i29g2000prf. googlegroups.com>,
berte <be********@gmail.comwrote:
>what's wrong this code ?
Almost eveything... But the most egregious error is this:
>typedef struct{
char *name;
int no;

}Person;

int main()
{
Person *s = NULL;

s = (Person *)malloc(sizeof(Person));

printf("name: ");
scanf("%s", &s->name);
Oops, you haven't allocated any space for the name, just a pointer to it.
And you're writing the read-in string over that pointer, instead of into
the (non-existent) memory pointed to by it. And how much memory do you need
anyway? The user could type an arbitrarily long name.

Perhaps you have only one misunderstanding here, and think that
scanf() with %s allocates a string. It doesn't; it reads a string
into some already-existing memory.

-- Richard
--
:wq
Dec 18 '07 #3
thanks your explanations.

i solved this problem. I have one problem now.
#include "transportInfo.h"

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>

static FILE *file = 0;

void openFile(const char *pFileName)
{
file = fopen(pFileName, "a");
if (!file)
{
printf("%s file is cannot open!!\n", pFileName);
exit(EXIT_FAILURE);
}
else
printf("%s file is open .\n", pFileName);
}

void addTransport(const TransportInfo *tpInfo)
{

fseek(file, 0L, SEEK_END);
fprintf(file,"%s\t%s\t%s\t%s\n", tpInfo->Country, tpInfo->City,
tpInfo->Railway, tpInfo->Population);
}

I use tihis code but it's not append on text. Do u have any idea this
stutation?

Thanks for reading,
best regards.
On 18 Aralęk, 02:16, berte <behzate...@gmail.comwrote:
what's wrong this code ?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

typedef struct{
char *name;
int no;

}Person;

int main()
{
Person *s = NULL;

s = (Person *)malloc(sizeof(Person));

printf("name: ");
scanf("%s", &s->name);
printf("number: ");
scanf("%d", &s->no);

printf("Name: %s Number: %d", s->name, s->no);

free(s);

system("pause");

return 0;

}
Dec 18 '07 #4
[Please don't top post, and don't hijack an existing thread
to start a new topic.]

berte <behzate...@gmail.comwrote:
thanks your explanations.

i solved this problem. I have one problem now.
#include "transportInfo.h"

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>
This is a non standard header.
static FILE *file = 0;
Why make this a global?
void openFile(const char *pFileName)
Return it, the way fopen() does.
{
file = fopen(pFileName, "a");
if (!file)
{
printf("%s file is cannot open!!\n", pFileName);
exit(EXIT_FAILURE);
}
else
printf("%s file is open .\n", pFileName);

}

void addTransport(const TransportInfo *tpInfo)
{
fseek(file, 0L, SEEK_END);
This is redundant since you opened the file with "a". If you're
going to leave it in, check if it is successful.
fprintf(file,"%s\t%s\t%s\t%s\n", tpInfo->Country, tpInfo->City,
tpInfo->Railway, tpInfo->Population);
Is population really a character string?

You should check that this is successful too.

Also, check fclose().
}

I use tihis code but it's not append on text.
Do u have any idea this stutation?
Since you haven't posted compilable code, we can only guess.

--
Peter
Dec 18 '07 #5
berte wrote:
what's wrong this code ?
There's always the danger when one tries to fix horribly broken code
that something will be overlooked or new errors introduced. In any
case, here's a first pass at correcting your code. And the answer to
your question is, "Almost everything."

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

typedef struct
{
char *name;
int no;

} Person;

int main()
{
Person *s = NULL;
const size_t namesize = 128; /* mha: added */

/* mha: small modification below */
if (!(s = malloc(sizeof *s))) {
fprintf(stderr,
"Could not allocate space for Person struct.\n"
"Giving up.\n");
exit(EXIT_FAILURE);
}
/* mha: but allocating space for name element is crucial */
if (!(s->name = malloc(namesize))) {
fprintf(stderr,
"Could not allocate space for s->name.\n"
"Giving up.\n");
exit(EXIT_FAILURE);
}

printf("name: ");
fflush(stdout); /* mha: added */

#if 0
/* mha: incredibly broken code below: */
scanf("%s", &s->name);
/* mha: replaced with (the still hopelessly unsafe): */
#endif
scanf("%s", s->name);

printf("number: ");
fflush(stdout); /* mha: added */
scanf("%d", &s->no);

/* mha: fixed missing end-of-line at end of last line of output */
printf("Name: %s Number: %d\n", s->name, s->no);

free(s->name); /* mha: added */
free(s);
/* mha: removed nonportable system call. (And there are better ways
to wait for a keypress if your broken environment makes doing that
wise.) */
return 0;
}

Dec 18 '07 #6
berte wrote:
[Please don't top post]
On 18 Aral?k, 02:16, berte <behzate...@gmail.comwrote:
>what's wrong this code ?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

typedef struct{
char *name;
int no;

}Person;

int main()
{
Person *s = NULL;

s = (Person *)malloc(sizeof(Person));

printf("name: ");
scanf("%s", &s->name);
printf("number: ");
scanf("%d", &s->no);

printf("Name: %s Number: %d", s->name, s->no);

free(s);

system("pause");

return 0;

}
thanks your explanations.

i solved this problem. I have one problem now.
You have more than one.
#include "transportInfo.h"

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>
This group cannot discuss transportInfo.h and conio.h. Therefore,
strictly speaking your code is incomplete and hence undefined as far as
this group is concerned.
static FILE *file = 0;
Try to remove file scope objects unless they are absolutely necessary.
Also 'file' is a poor name choice. Taking advantage of C's case
sensitivity to name your identifiers is not wise.
void openFile(const char *pFileName)
{
file = fopen(pFileName, "a");
if (!file)
{
printf("%s file is cannot open!!\n", pFileName);
exit(EXIT_FAILURE);
}
else
printf("%s file is open .\n", pFileName);
}

void addTransport(const TransportInfo *tpInfo)
{

fseek(file, 0L, SEEK_END);
You should also check fseek for errors. In C, for robust code, you need
to check each and every invocation of every function that could return
a status result. Also since you opened the file with append mode, the
file pointer is already positioned correctly at this point and your
above seek is unnecessary.
fprintf(file,"%s\t%s\t%s\t%s\n", tpInfo->Country, tpInfo->City,
tpInfo->Railway, tpInfo->Population);
}

I use tihis code but it's not append on text. Do u have any idea this
stutation?
Please post a minimised, compilable example that exhibits your problem.
You may even discover the problem yourself during the minimising
process. It's generally not possible to give good advice based on
incomplete code. Also please copy and paste from your editor, otherwise
the possibility of silly little typos is too high.

Dec 18 '07 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: raulgz | last post by:
hi I need generate dinamic sql: I need a select sentence with all fields of one table 't1' and all fields of tables which 't1' have foreings keys 't1 ( reflexive ) ,t2,t3,...' Now, l have de...
1
by: dddddd | last post by:
i need do create simple dinamic site - built mainly of pictures(they are the only dinamic part). pictuers differ by the -Location- and by -Time- (in which they were taken)... so on the index...
6
by: gp | last post by:
Hi all, I'm using Microsoft Visual C++ 6.0, I would like to see, debugging my project, all the elements of my dinamic objects.... I have a dinamic array and a STL vector and I need to know...
7
by: Morgan | last post by:
I have read much posts on the argument but no one clearly says if this operation is possible or not. Simply I have a routine which reads from a text file some integer arrays (1 or 2D). The...
3
by: Jose Garcia | last post by:
Hi there, Can somebody explain me how can i use matrixes with dinamic memory? I use malloc and free (NOT new & delete). I want to access to the matrix like Matrix but i don't know how to do that...
10
by: javuchi | last post by:
I just want to share some code with you, and have some comments and improvements if you want. This header file allocates and add and delete items of any kind of data from a very fast array: ...
0
by: Juan Segura | last post by:
Hello: I developing a filter for ISA Server. This filter is a dinamic dll not compatible with clr (Common Language Runtime). I'm trying to make a dimanic dll compatible with clr and call it...
1
by: cuti | last post by:
hi, i have to allocate dynamically the vectors in the structure: typedef struct { float *x; float *y; float *y2; int max_val;
25
by: stararic | last post by:
hi, I'm writing a program a kind of calculator that should work with very big numbers (thousand of digits). So, numbers are rappresented by a struct that contains a pointer to integer, e 2 int for...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.