Romper la cuerda y almacenarla en una matriz

I want to break down a sentence and store each string in an array. Here is my code:

#include <stdio.h>
#include <string.h>

int main(void)
{
    int i = 0;
    char* strArray[40];
    char* writablestring= "The C Programming Language";
    char *token = strtok(writablestring, " ");


    while(token != NULL)
    {
        strcpy(strArray[i], token);
        printf("[%s]\n", token);
        token = strtok(NULL, " ");
        i++;
    }
    return 0;
}

It keeps giving me segmentation error and I cannot figure it out. I believe it has something to do when I copy the token to my array.

preguntado el 08 de noviembre de 11 a las 19:11

2 Respuestas

Eso es porque writablestring isn't writable at all. Attempting to write to a string literal is undefined behavior and strtok writes to it (that's right, strtok modifies its argument).

To make it work, try:

char writablestring[] = "The C Programming Language";

También hay un C Preguntas frecuentes.

Another problem is that you didn't allocate memory for your array of character pointers (so those pointers point to nothing).

char* strArray[40]; /* Array of 40 char pointers, pointing to nothing. */

Maybe try this ?

/* Careful, strdup is nonstandard. */
strArray[i] = strdup(token);

/* Or this. */
strArray[i] = malloc(strlen(token) + 1);
strcpy(strArray[i], token);

respondido 08 nov., 11:23

Echa un vistazo a the example in the docs:

char * strtok ( char * str, const char * delimiters );

...donde...

str - C string to truncate. The contents of this string are modified and broken into smaller strings (tokens). Alternativelly, a null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended.

delimitadores - C string containing the delimiters. These may vary from one call to another.

Valor de retorno - A pointer to the last token found in string. A null pointer is returned if there are no tokens left to retrieve.

You need that first string to me modifiable and you need to allocate memory for the outputs e.g.

int main(void)
{
    int i = 0;
    const int numOfStrings = 128;
    char* strArray[numOfStrings];
    char writablestring[]= "The C Programming Language";
    char *token = strtok(writablestring, " ");

    for( int j = 0; j < numOfStrings; j++ )
    {
        strArray[j] = new char[40];
    }

    while(token != NULL)
    {
        strcpy(strArray[i], token);
        printf("[%s]\n", token);
        token = strtok(NULL, " ");
        i++;
    }
    return 0;
}

respondido 08 nov., 11:23

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.