Reputation: 428
It's been a while that I haven't written programs in C. I am used to write code in C#.
So, I want to split the user string input into an array of strings using a delimiter. I did this, but when I want to fetch the array I have a segmentation fault. As an example, I want just to print one element of the array.
I have checked on the net, but nothing worked.
Any hints ?
Thanks
#include<stdio.h>
#include<string.h>
int main ()
{
char function[] = {};
char * pch;
int cpt = 0;
int nb_terms = 0;
printf("Entrez le nombre de termes :\n");
scanf("%d", &nb_terms);
char word[nb_terms];
printf("Entrez votre fonction en n'utilisant que les 5 caractères suivants (a,b,c,d et +) :\n");
scanf("%s", &function);
pch = strtok (function,"+");
while (pch != NULL)
{
word[cpt++] = pch;
printf ("%s\n",pch);
pch = strtok (NULL, "+");
}
printf ("%s\n",&word[1]);
return 0;
}
Upvotes: 0
Views: 91
Reputation: 164639
Compiler warnings reveal your problems.
cc -Wall -Wshadow -Wwrite-strings -Wextra -Wconversion -std=c99 -pedantic -g -c -o test.o test.c
test.c:7:21: warning: use of GNU empty initializer extension [-Wgnu-empty-initializer]
char function[] = {};
^
test.c:7:21: warning: zero size arrays are an extension [-Wzero-length-array]
test.c:18:15: warning: format specifies type 'char *' but the argument has type 'char (*)[0]'
[-Wformat]
scanf("%s", &function);
~~ ^~~~~~~~~
These are all related. char function[] = {}
is a GNU extension to declare a 0 size array. Then you try to put stuff into it, but it's size 0. So there's going to be an overflow.
Instead, you need to allocate some space to function
and be sure to limit scanf
to only that size, no larger.
// {0} initializes all characters to 0.
// 1024 is a good size for a static input buffer.
char function[1024] = {0};
// one less because of the null byte
scanf("%1023s", &function);
The next warning...
test.c:23:17: warning: incompatible pointer to integer conversion assigning to 'char' from 'char *';
dereference with * [-Wint-conversion]
word[cpt++] = pch;
^ ~~~
*
is because you're trying to put the string (char *
) pch
where a character (char
) goes. Even if you're only reading a single character from strtok
(which you cannot guarantee) it always returns a string. You want an array of strings (char **
). It also helps to have descriptive variable names.
char *word; // this was pch
char *words[nb_terms]; // this was word
After changing pch
to word
, and word
to words
in the rest of the code it all works.
size_t word_idx = 0;
for(
char *word = strtok(function,"+");
word != NULL;
word = strtok(NULL, "+")
) {
words[word_idx++] = word;
}
I'll add the usual caveats about scanf
.
Upvotes: 2