Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you fill an array with strings in C?

Tags:

c

I'm trying to fill an array with names from a file:

Andrew
Andy
Bob
Dan
Derek
Joe
Pete
Richy
Steve
Tyler

Here is the function I wrote...but the program crashes when I run it:

#include <stdio.h>

main(){
  int i=0, size=10;
  char fname[15];
  char** data;
  char* name;
  FILE* fp;

  printf("Enter a filename to read names:\n");
  scanf("%s", fname);

  fp = fopen(fname, "r");
  if(fp == NULL)
    exit();

  data = (char**)malloc(sizeof(char**)*size);

  while(!feof(fp)){
    fscanf(fp, "%s", name);
    data[i] = (char*)malloc(sizeof(name));
    data[i] = name;
    i++;
  }

  fclose(fp);

  printf("\n\n");

  for(i=0; i<size; i++)
    printf("%s ", data[i]);

  free(data);
}

Anyone know what I'm doing wrong? Thanks

like image 978
Andrew Avatar asked Dec 23 '22 05:12

Andrew


1 Answers

You have a couple of errors here:

1) You never allocate memory where name will get stored. You could get around this simply by using:

char name[128];

Then, when you use fscanf, you'd have:

fscanf(fp, "%127s", name); // stores this in name correctly, now...

2) You're inappropriately allocating space for data[i]:

data[i] = (char*)malloc(sizeof(name));

This will allocate space to hold one pointer to char (char*), since name is a char*. You need to be doing:

data[i] = (char*)malloc(sizeof(char) * (strlen(name) + 1 ) );

This will allocate enough space for the data plus a single terminating character.

3) You aren't assigning data[i] correctly. You can't just use = here, but need to use strcpy:

strcpy(data[i], name);

4) You're not freeing the individual pointers in the data[..] elements. You should add, after your printf, a free:

for(i=0; i<size; i++)
{
    printf("%s ", data[i]);
    free(data[i]);  // Free each pointer you allocate
}

Every malloc call should eventually have a matching free call.

like image 184
Reed Copsey Avatar answered Jan 06 '23 01:01

Reed Copsey