连接一个单词 n 次

Concatenate a word n times

我怎样才能做这样的事情?

x = abc
x^1 = abc
x^2 = abcabc
x^3 = abcabcabc

我尝试在 for 循环中使用 strcat 函数,但它不起作用。

int potw2;
char w2[100];
w2="abc";
potw2 = 5;
potenciarw2(w2, potw2);

void potenciarw2(char *pal, int potw2) {
    for (int i = 0 ; i < potw2 ; i++) {
        strcat(pal, pal);
    }
    printf("La palabra es:%s\n",pal);       
}

不要为此使用 strcat(),我的意思是对于已知长度的字符串的增量连接,我几乎想不出 strcat() 真正有用的情况,有一些情况但通常这样会更好、更有效,例如

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

char *pow_string(const char *const source, int times)
{
    size_t length;
    char *result;
    length = strlen(source);
    result = malloc(length * times + 1);
    if (result == NULL)
        return NULL;
    for (int index = 0 ; index < times ; ++index)
        memcpy(result + index * length, source, length);
    result[length * times] = '[=10=]';
    return result;
}

int
input_error()
{
    fprintf(stderr, "error de entrada, ha introducido texto inválido\n");
    return -1;
}

int
main(void)
{
    char *result;
    int power;
    char word[100];
    fprintf(stdout, "Ingrese un texto (máx 99 caracteres) > ");
    if (scanf("%99[^\n]", word) != 1)
        return input_error();
    fprintf(stdout, "Cuántas veces quiere repetir la palabra ? ");
    if (scanf("%d%*[ \t]", &power) != 1)
        return input_error();
    result = pow_string(word, power);
    if (result == NULL)
        return -1;
    fprintf(stdout, "%s\n", result);
    /* free `result' which was allocated with `malloc()' */
    free(result);
    return 0;
}

strcat() 预计目标和源 不会 重叠。也就是说,strcat()的两个参数不能指向同一个内存。

您需要为结果字符串分配新内存,并在循环中使用memcpy

void potenciarw2(char *pal, int potw2)
{
    size_t len = strlen(pal);
    char* result = malloc(len * potw2 + 1); // allocate enough memory for the resulting string and null char
    if (result == NULL) {
        fputs("malloc() ha fallado", stdout);
        return;
    }

    for (int i = 0 ; i < potw2 ; i++) {
        memcpy(result + i * len, pal, len); // concatenate string using memcpy
    }

    result[len * potw2] = '[=10=]'; // terminate with null char

    printf("La palabra es:%s\n",result);

    free(result);
}

您的函数需要稍作修改才能运行。修改如下:

void potenciarw2(char *pal, int potw2) {

    /* allocate some memory and copy to it*/
    char buffer[100];

    strcpy(buffer,pal);

    for (int i = 0 ; i < potw2 ; i++) {
        strcat(buffer, pal);/*now you can use strcat() safely*/
    }

    /*copy data back to pal*/
    strcpy(pal,buffer);
    printf("La palabra es:%s\n",pal);       
}

int main(void)
{

    int potw2;
    char w2[100] = "abc";
    potw2 = 3;
    potenciarw2(w2, potw2);

}