I'm learning C by myself and I'm trying to use my knowledge (i.e. no library use) to create a program that does the following:
- Split a string into words (words are separated by spaces)
- Put each word in an array
So, in the end, I must have an array of strings (an array of array of chars).
This is my code:
#include <stdio.h>
int main () {
int i, conta, indice_completo=0, indice_nome=0, indice_caractere=0;
char nome [90], nomevetor [30] [90];
scanf ("%[^\n]s", nome);
while (nome[indice_completo] != '\0') {
while (nome[indice_completo] != ' ' && nome [indice_completo] != '\0') {
nomevetor [indice_nome] [indice_caractere] = nome [indice_completo];
indice_completo++;
indice_caractere++;
}
nomevetor [indice_nome] [indice_caractere] = '\0';
indice_caractere=0;
indice_nome++;
}
conta=indice_nome;
for (i=0 ; i<conta; i++) {
printf ("Nome %d: %s\n", i+1, nomevetor [i]);
}
return 0;
}
But when I compile it using:
gcc -ansi -Wall -g programa.c -o programa
I get segmentation fault.
- Why did I get segmentation fault?
- Is my algorithm correct?
- Is there a better way to do what I want?