N00B. I keep getting a segmentation fault when I try to substitute a word with another. I'm using this tutorial as an example but don't seem to get it right: http://www.cplusplus.com/reference/clibrary/cstring/strstr/

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

void REPLACE(char STRING[])
{
	char *MONTH[] = {"January","February","March","April","May","June","July","August","September","October","November","December"};
	char *MES[] = {"Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"};

	int B = 0;

	while(B < 12)
	{
		if ( strstr(STRING, MONTH[B]) )
		{
			char *pch;
			pch = strstr(STRING, MONTH[B]);
			strncpy(pch, MES[B], strlen(MES[B]) ); // Segmentation fault
			puts(STRING);
		}

		B++;
	}
}

int main (void)
{
	REPLACE("The month is: January."); // Should be: "The month is: Enero"

	return 0;
}

Recommended Answers

All 2 Replies

This is array of pointers to string literals:

char *MONTH[] = {"January","February","March","April","May","June","July","August","September","October","November","December"};

String literals are not writable.

Same here:

REPLACE("The month is: January."); // Should be: "The month is: Enero"

MONTH and MES are arrays of pointers to read-only memory.
The value they are pointing to it can not be modified. It works the same way than if it were single pointers.

char *dia = "Lunes"; /* Lunes can not be changed because is a piece of memory fixed as read-only */

Lunes has been created and dia points to it, but you can not modified it.

char dia[] = "Martes" /* Martes is a piece of memory that you can modify */
char *jornada = dia; /* jornada points to dia which is a piece of memory that can be modified */
strcpy(jornada, "Lunes"); /* Now dia has Lunes */
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.