Reputation: 21
Ok, here's some overview about what I'm trying to achieve. I want the user to be able to enter any amount of strings, and then I want to save those strings in a double char pointer. At the moment I haven't dealt with scaling my memory allocation for my double char pointer because I want to get it working first.
char **list = malloc(sizeof(char*)*5);
for(i = 1; i < argc; i++) {
strcpy(list[i], argv[i]);
}
I honestly thought this was going to be simple, so hopefully I'm making some stupid mistake. I keep receiving a seg fault error at the strcpy function.
Upvotes: 1
Views: 79
Reputation: 6531
What you did is only allocated memory for array of pointers to strings (which is correct), but you also need to allocate memory for each string in your array:
First (simpler) option:
char **list = malloc(sizeof(char*) * argc);
for(i = 1; i < argc; i++)
{
list[i] = strdup(argv[i]);
}
second (more complex) option:
size_t n = 0;
char **list = malloc(sizeof(char*) * argc);
for(i = 1; i < argc; i++)
{
n = strlen(argv[i]) + 1;
list[i] = malloc(n);
strcpy(list[i],argv[i]));
}
Upvotes: 3
Reputation: 5706
It's not correctly malloced you only malloced the main pointer not the other ones.
Try this
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(int argc, char **argv) {
char **list = malloc(sizeof(char*)*argc);
int i;
for(i = 0; i < argc-1; i++) {
list[i] = malloc(sizeof(char) * (strlen(argv[i+1]) + 1));
strcpy(list[i], argv[i+1]);
printf("%s\n", list[i]);
}
return 0;
}
EDIT I forget the v in argv
EDIT (working copy edited above) output below
./temp hello this is a list of arguments
hello
this
is
a
list
of
arguments
Upvotes: 0
Reputation: 224944
You've allocated an array of pointers to strings, but you haven't allocated any space for the strings themselves. Every time you call strcpy()
, you're passing it an uninitialized destination pointer. Add a line to the beginning of your loop:
list[i] = malloc(strlen(argv[i]) + 1);
If you want it to work for any number of strings, your initial allocation has to be:
char **list = malloc(sizeof(char *) * argc);
Upvotes: 0