Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

C noob, garbled string problem,.. 1

Status
Not open for further replies.

marsd

IS-IT--Management
Apr 25, 2001
2,218
US
I've been working with C a little over the weekend and
experimenting with pointers. This is not a matter of life and death, I'd just like to know where my mistake is.

Code looks like this:
#include <stdio.h>
#include <stdlib.h>

struct asinine {
char *str[25];
int *p1;
int p2;
};

/*function protos*/
struct asinine *RetPt(void);
void printall(struct asinine *ptr);

int main(void) {
struct asinine *pret;
int j;
/*allocate memory for container structure*/
pret = (struct asinine *)malloc(sizeof(struct asinine));

/*test the function for a while*/
if (pret) {
for (j=1 ; j <=3 ; j++) {
pret = RetPt();
printall(pret);
}
}
/* all done*/
return 0;
}

struct asinine *RetPt(void) {
/* ptr struct to pass to printall and main */
struct asinine *ret;
char buf[25];

puts(&quot;String value for asinine: &quot;);
/*gets(buf);
if (strlen(buf) < 26) {
strcpy(ret->str,buf);
} no difference.*/
scanf(&quot; %s&quot;, &ret->str);
/* str loaded*/
putchar('\n');
puts(&quot;First int value: &quot;);
scanf(&quot; %d&quot;, &ret->p1);
/*first integer */
putchar('\n');
puts(&quot;Second, and last int value: &quot;);
/* second integer */
scanf(&quot; %d&quot;, &ret->p2);
putchar('\n');

return ret;
}

void printall(struct asinine *p) {
/* prints struct members*/
printf(&quot;String value:%s ,is given in adjacency with %d , #1 and , %d, #2.\n&quot;,p->str,p->p1,p->p2);
}

A sample run looks like:
String value for asinine:
thisnthat

First int value:
12

Second, and last int value:
35

String value:èõÿ¿nthat ,is given in adjacency with 12 , #1 and , 35, #2.

Why the garbled chars?

Thanks.
 
Some notes:
1) You don't allocate any space for your ret variable in your RetPt function.
2) You shouldn't use the address operator (&) infront of string variables (as these are already pointers).
3) You don't free the space of pret before it gets assigned to new memory.
4) Also, your str member of the asinine is created as an array of pointers to chars, but you are using it as if it was a string.
The ones that could cause your troubles are 1, 2 and 4. //Daniel
 
Thanks for the tips, very helpful for a
newbie.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top