Reputation: 381
I am trying to place a string into the structure index 0 inside a structure array but i keep on segmentation fault. Anyone know whats going on?? I tokenize the string by comma,sending the name and age token to a function that builds the array, the function should enter the name and number into the structure but every time i try to add a entry into the structure array from outside where it was declared i get segmentation faults so am i trying to enter these elements incorrectly?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct info{
char name[20];
int age;
};
void buildarray(struct info array[],char* namee,char* age);
int main()
{
struct info arrays[3];
char buffer[] = "john,25";
char* del = ",";
char* token;
char* number;
char* name;
token = strtok(buffer,del);
name = token;
while(token != NULL)
{
token = strtok(NULL,del);
number = token;
}
buildarray(arrays,name,number);
printf("%s %d",arrays[0].name,arrays[0].age);
}
void buildarray(struct info array[],char* namee,char* age)
{
char buffer[10];
strcpy(array[0].name,namee);
int amount = atoi(age);
array[0].age = amount;
}
Upvotes: 0
Views: 70
Reputation: 182769
while(token != NULL)
{
token = strtok(NULL,del);
number = token;
}
buildarray(arrays,name,number);
On the last pass, when token
is NULL
, number
is NULL
too. You then call buildarray
passing it a NULL
, which it passes to atoi
. Boom.
Upvotes: 4