简体   繁体   English

用C乘以字符串

[英]Multiply strings in C

I wrote a simple program to multiply a string a defined times. 我编写了一个简单的程序来将字符串乘以定义的次数。 But, it doesn't really work, and don't know why... 但是,它并没有真正起作用,也不知道为什么...

It's so simple that I don't know what the problem could be... 非常简单,我不知道问题可能在哪里...

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

char *product(char *str, int k);

int main()
{
    char strg[1000];
    char *prod;
    int mult;

    scanf("%s", strg);
    scanf("%d", mult);

    prod = product(strg, mult);

    printf("%s\n", prod);

    return EXIT_SUCCESS;
}

char *product(char *str, int k)
{
    int i, j;
    int len = strlen(str);
    char *res = (char *) malloc(sizeof(char) * (len * k + 1));

    for (i = 0, j = 0; i < (len * k); i++, j++)
    {
            if (j == len) j = 0;

            res[i] = str[j];
    }

    res[++i] = '\0';

    return res;
}

Anyone who can help me to figure out where's the problem? 谁能帮助我找出问题所在? :D :D

At the end of the loop, i is already the index of the position for the terminator. 在循环结束时, i已经是终止符位置的索引。

Just do 做就是了

res[i] = 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM