PDA

View Full Version : C programming - bus error


coderyc
03-22-2010, 07:12 PM
Hello,

I am getting a bus error when I run the following code:
I dont understand why I get a bus error??

#include <stdio.h>

#define MAX_ENTRIES 100

typedef struct ContactRecord
{
char name[16]; /*structure member*/
unsigned char number[20]; /*structure member*/
}Contact; /*Contact is a structure variable of type ContactRecord*/

static Contact ContactTable[MAX_ENTRIES];

void edit_record(char *, char *);

main()
{
char name [] = "johnsmith";
char number[] = "1234567891234567890";

edit_record(&name, &number);
}

void edit_record(char *ptrname, char *ptrnumber)
{
int i=0, j=0;

for (j = 0; j<= 16; j++)
ContactTable[i].name[j] = ptrname[j];
for (j=0; j<= 20; j++)
ContactTable[i].number[j] = ptrnumber[j];
for (j = 0; j<= 16; j++)
printf("%s\n",ContactTable[i].name[j]);
}

CrzySdrs
03-22-2010, 07:54 PM
The only mistake you made was not using printf with a pointer to a string. You were giving characters which it was attempting to dereference.




void edit_record(char *ptrname, char *ptrnumber)
{
int i=0, j=0;

for (j = 0; j< 16; j++)
ContactTable[i].name[j] = ptrname[j];
for (j=0; j< 20; j++)
ContactTable[i].number[j] = ptrnumber[j];

printf("%s\n",ContactTable[i].name);
}


A few notes about your code, you should really be using the string functions, like strcpy to copy the strings from one location to another (I highly suggest using strncpy). Also, be wary of leaving space for the null if you use the string functions since that is a pretty common mistake. With a few changes, your code becomes much easier to read:


void edit_record(char *ptrname, char *ptrnumber)
{
int i=0, j=0;

strcpy( ContactTable[i].name,ptrname);
strcpy( ContactTable[i].number, ptrnumber);

printf("%s\n",ContactTable[i].name);
}

oracleguy
03-22-2010, 07:54 PM
I don't know what you mean by "bus error".

However you are reading past the ends of those arrays which is bad. You should also look up the strcpy function. You also don't need the ampersands before the character arrays when you call edit record, they are arrays and as such already pointers. You should also have a return type on your main function.