473,408 Members | 1,908 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,408 software developers and data experts.

Pointers again...

i have this little .c, it's in spanish but you'll get it anyway

#include <stdio.h>
typedef struct {
char cadena[20];
int enterito;
} registro;

//this puts a new element to the list
int agregarElemento(registro **lista, registro *aux, int *lMax);
int main(void) {
registro **lista;
registro *aux;
int lMax;
int i,a,j;
char buf[15];
//creo una lista de 1 posicion
// i put a single element first
lista = (registro**) malloc (sizeof(registro*));
aux = (registro*) malloc(sizeof(registro));
aux->enterito = 0;
strcpy(aux->cadena, "Cadena_0\0");
lista[0]=aux;

printf("Cadena: %s y el numero es: %d\n",lista[0]->cadena,
lista[0]->enterito);

lMax = 1;

// i'll put N elements more.
//agrego N elementos MAS hasta 0.

printf("Ingresa un numero:\n");
scanf("%s",buf);
j = atoi(buf);

while (j)
{

for (i=0; i< j ; i++)
{
//i fill a record.
sprintf(buf,"Cadena_%d\0",lMax);
aux = (registro*) malloc(sizeof(registro));
aux->enterito = lMax;
strcpy(aux->cadena,buf );
// This is the line that's bugging me ////////////////////////////
lista = (registro**) realloc ( lista, sizeof(registro*) * ((lMax)+1)
);
agregarElemento(lista,aux,&lMax);

}

printf("Ingresa un numero:\n");
scanf("%s",buf);
j = atoi(buf);

}

for (i=0; i< lMax; i++) printf("Cadena: %s y el numero es:
%d\n",lista[i]->cadena, lista[i]->enterito);

return 1;
}
int agregarElemento(registro **lista, registro *aux, int *lMax)
{
lista[*lMax]=aux;
(*lMax)++;
return *lMax;
}
Ok, this works fine, i mean, i can add and print as many items as i
want BUT!
if i want to take the Realloc of the Index (pointer to pointer var.) to
a function like "agregarElemento" <add element >, eventualy it SEGS
FAULT . So there must be something i dont know about pointers, what
happens when you pass it to a function outside ? Because when i do
....... BUM!
If you want i can post a version of the software that fails. I guess
the question is:

How can i make a safe <add_a_element> function?

Apr 21 '06 #1
2 1673
if*****@gmail.com schrieb:
i have this little .c, it's in spanish but you'll get it anyway

#include <stdio.h>
typedef struct {
char cadena[20];
Magic number: Use a symbolic constant instead
#define CADENA_LENGTH 19
....
char cadena[CADENA_LENGTH+1];
where the +1 stems from the string terminator and
CADENA_LENGTH is the usable number of bits.
int enterito;
} registro;

//this puts a new element to the list
int agregarElemento(registro **lista, registro *aux, int *lMax);
int main(void) {
registro **lista;
registro *aux;
int lMax;
int i,a,j;
char buf[15];
//creo una lista de 1 posicion
// i put a single element first
lista = (registro**) malloc (sizeof(registro*));
aux = (registro*) malloc(sizeof(registro));
The cast is unnecessary in C; in addition, this breaks
easily if you change the type. The best practice form around
here is
lista = malloc(sizeof *lista);
aux = malloc(sizeof *aux);
Of course you can put parentheses around *lista and *aux if
that makes you feel more comfortable.
aux->enterito = 0;
Serious error: You did not check whether aux and lista are
!= NULL. You may already have invoked undefined behaviour.
Everything is possible from now on.
strcpy(aux->cadena, "Cadena_0\0");
lista[0]=aux;

printf("Cadena: %s y el numero es: %d\n",lista[0]->cadena,
lista[0]->enterito);

lMax = 1;

// i'll put N elements more.
//agrego N elementos MAS hasta 0.

printf("Ingresa un numero:\n");
scanf("%s",buf);
j = atoi(buf);
Bad choice for input. Consider fgets() and strtol() instead -- they
give you much better information if it comes to finding errors.
while (j)
{

for (i=0; i< j ; i++)
{
//i fill a record.
sprintf(buf,"Cadena_%d\0",lMax);
If you have snprintf(), use it instead.
Otherwise, restrict lMax in a way that makes sure that
Cadena_%d cannot exceed CADENA_LENGTH.
aux = (registro*) malloc(sizeof(registro));
aux->enterito = lMax;
strcpy(aux->cadena,buf );
// This is the line that's bugging me ////////////////////////////
lista = (registro**) realloc ( lista, sizeof(registro*) * ((lMax)+1)
);
You need a temporary variable:
registro **tmp;

....
tmp = realloc (lista, (lMax + 1) * sizeof *tmp);
if (tmp == NULL) {
/* Your error handling here; either break out of the loop
** or exit afterwards. */
}
lista = tmp;
By the way: Why do you not store all registro objects in one array
instead of storing pointers to them in an array?
If you really need to do it this way, then at least do not realloc()
unnecessarily much:
while (j) {
int i;
registro **tmp = realloc (lista, (lMax + j) * sizeof *tmp);
if (tmp == NULL) {
fprintf(stderr, "Memory allocation failed for list extension "
"from %d to %d\n", lMax, lMax + j);
break;
}
lista = tmp;
for (i = 0; i < j; i++) {
lista[lMax + i] = NULL;
}
for (i = 0; i < j; i++) {
if ((aux = malloc(sizeof *aux)) == NULL) {
fprintf(stderr, "Memory allocation failed for list member "
"at %d\n", lMax+i);
break;
}
lista[lMax] = aux;
/* Init *aux */
++lMax;
}
if (aux == NULL)
break;
....
agregarElemento(lista,aux,&lMax);

} <snip>
I did not consider the rest.
Ok, this works fine, i mean, i can add and print as many items as i
want BUT!
if i want to take the Realloc of the Index (pointer to pointer var.) to
a function like "agregarElemento" <add element >, eventualy it SEGS
FAULT . So there must be something i dont know about pointers, what
happens when you pass it to a function outside ? Because when i do
...... BUM!


If you want to modify an object (in this case lista), then pass its
address; i.e. you need a registro *** parameter.
In addition, you have to admit the possibility of failure, so give
agregarElemento a return value indicating success or failure _and_
_check_ _it_!
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Apr 21 '06 #2
Michael Mair wrote:
if*****@gmail.com schrieb:
i have this little .c, it's in spanish but you'll get it anyway

#include <stdio.h>
typedef struct {
char cadena[20];
<snip>
//creo una lista de 1 posicion
// i put a single element first
lista = (registro**) malloc (sizeof(registro*));
aux = (registro*) malloc(sizeof(registro));
The cast is unnecessary in C; in addition, this breaks
easily if you change the type.


You failed to mention that it hides the error of failing to include
stdlib.h which, from the code shown, is an error the OP has made.
The best practice form around
here is
lista = malloc(sizeof *lista);
aux = malloc(sizeof *aux);
Of course you can put parentheses around *lista and *aux if
that makes you feel more comfortable.


<snip>
printf("Ingresa un numero:\n");
scanf("%s",buf);
j = atoi(buf);


Bad choice for input. Consider fgets() and strtol() instead -- they
give you much better information if it comes to finding errors.


Also, the way the OP used scanf is equivalent to using gets and allows
the user of the program to overflow the buffer.
while (j)
{

for (i=0; i< j ; i++)
{
//i fill a record.
sprintf(buf,"Cadena_%d\0",lMax);


If you have snprintf(), use it instead.


<snip>

Be aware that some implementations that provide snprintf as an extension
to C89 (the commonly implemented C standard) use different return values
to others.
--
Flash Gordon, living in interesting times.
Web site - http://home.flash-gordon.me.uk/
comp.lang.c posting guidelines and intro:
http://clc-wiki.net/wiki/Intro_to_clc
Apr 21 '06 #3

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

Similar topics

9
by: wongjoekmeu | last post by:
Hello All, I am learning C++ at the moment. Going through the book of SAM of learning C++ in 21 days I have learned about pointers that it is good custome to always initialise them and to use...
388
by: maniac | last post by:
Hey guys, I'm new here, just a simple question. I'm learning to Program in C, and I was recommended a book called, "Mastering C Pointers", just asking if any of you have read it, and if it's...
7
by: Rano | last post by:
/* Hello, I've got some troubles with a stupid program... In fact, I just start with the C language and sometime I don't understand how I really have to use malloc. I've readden the FAQ...
92
by: Jim Langston | last post by:
Someone made the statement in a newsgroup that most C++ programmers use smart pointers. His actual phrase was "most of us" but I really don't think that most C++ programmers use smart pointers,...
23
by: sandy | last post by:
I need (okay, I want) to make a dynamic array of my class 'Directory', within my class Directory (Can you already smell disaster?) Each Directory can have subdirectories so I thought to put these...
11
by: subramanian100in | last post by:
Given that the sizes of pointers to different data types(built-in or structures) can be different, though malloc returns a void *, it is assigned to any pointer type. The language allows it. From...
4
by: Josefo | last post by:
Hello, is someone so kind to tell me why I am getting the following errors ? vector_static_function.c:20: error: expected constructor, destructor, or type conversion before '.' token...
25
by: J Caesar | last post by:
In C you can compare two pointers, p<q, as long as they come from the same array or the same malloc()ated block. Otherwise you can't. What I'd like to do is write a function int comparable(void...
54
by: Boris | last post by:
I had a 3 hours meeting today with some fellow programmers that are partly not convinced about using smart pointers in C++. Their main concern is a possible performance impact. I've been explaining...
3
by: Jim | last post by:
Ok, I'm having 'fun' with pointers to structures. I've got some code that looks something like this: ==================== typedef struct { unsigned long *clno, *lastHistoryRecord; } aRecord;
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
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,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

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.