Martin B. Martin B. - 15 days ago 6
C Question

Printing arraylist size crash

I have a C program that implement arraylist (dynamic array,however I dont understand how or why i cannot print the array size.When I try to do so, the program just crash.Heres the program.

arraylist.c

#include "arraylist.h"

void arraylist_initial(struct arraylist *list) {
list->size = 0;
list->data = NULL;
}

int arraylist_get_size(const struct arraylist list) {
return list.size;
}

value_type* arraylist_get_data_collection(const struct arraylist list) {
return list.data;
}

void arraylist_set_data_collection(struct arraylist *list, value_type* data) {
list->data = data;
}

void arraylist_add(struct arraylist *list, value_type value) {
int size = arraylist_get_size(*list);
value_type *new_data;

new_data = realloc(list->data, (size + 1) * sizeof new_data[0]);

if (new_data)
{
new_data[size] = value;
arraylist_set_data_collection(list, new_data);
++list->size;
}
}

value_type arraylist_get(const struct arraylist list, int index) {
if(index < arraylist_get_size(list)) {
return list.data[index];
}
else {
return NULL;
}
}

int arraylist_indexof(const struct arraylist list, value_type value) {
int index = 0;
for(; index != arraylist_get_size(list); ++index) {
if(strcmp(list.data[index], value) == 0) {
return index;
}
}

return -1;
}

int main(void){
struct arraylist list;

arraylist_initial(&list);

arraylist_add(&list, "1");
arraylist_add(&list, "2");
arraylist_add(&list, "3");
arraylist_add(&list, "4");
arraylist_add(&list, "5");
arraylist_add(&list, "6");
arraylist_add(&list, "7");
arraylist_get_size(list);


int index = 0;
for(; index != 8; ++index) {
printf("CHECK: %s\n", arraylist_get(list, index));

}

return 0;
}


arraylist.h

#define _ARRAYLIST_H

#include <stdio.h>

typedef char* value_type;

struct arraylist {
int size;
value_type* data;
};

extern void arraylist_initial(struct arraylist *list);
extern int arraylist_get_size(const struct arraylist list);
extern value_type* arraylist_get_data_collection(const struct arraylist list);
extern void arraylist_set_data_collection(struct arraylist *list, value_type* data);
extern void arraylist_add(struct arraylist *list, value_type value);
extern value_type arraylist_get(const struct arraylist list, int index);
extern int arraylist_indexof(const struct arraylist list, value_type value);


In arraylist.c if I do

printf(arraylist_get_size_list(list));


It just crash and I dont get it?

thank you

Answer

Sorry, I was remembering a time when you couldn't pass structs with C. It looks like you can now. They keep changing things.

Here's the real problem: printf takes a string as the first argument.

Instead of:

printf(arraylist_get_size_list(list));

Try:

printf("size: %d\n", arraylist_get_size_list(list));
Comments