c - C中的数组反向输出

标签 c arrays loops reverse

我编写的程序接收来自字符串和子字符串的输入,然后通过确定子字符串出现的频率(出现次数)及其所在的位置来搜索字符串中的子字符串,然后插入这些位置例如到一个数组中(4 5 8)并且它们被正确打印,现在我正在尝试做的事情,一旦我在找到子字符串的位置内得到了我的数组,它就会反向打印它即(8 5 4)我尝试使用这个循环

// reverse output
printf ("%d", count);
for (j = count - 1; j >= 0; j--)
    printf("%d", pos[j]);

但是如果数组位置是 8 5 4 那么它会打印给我

5 ,4, -311228772

为什么会发生这种情况?这是代码:

// inclusion of libraries
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*
 Reads a string allocated by the stream.
 It stops at newline, not included in string.
 Returns NULL to EOF
 */
char *my_getline(FILE *stream) { // statement of function
    char *line = NULL; // this is just the pointer initialization
    size_t pos = 0; // definition of position variables and init
    int c; // a variable to store the temporary character
    while ((c = getc(stream)) != EOF) // read every character until the end of the file
    {
        char *newp = realloc(line, pos + 2); // To dynamically allocate memory, with reference to the number of characters and more '2' is only to compensate for the null character and the character (since it is 0)
        if (newp == NULL) { // checks whether memory has been properly associated or not.
            free(line); // if the line is not free the blank
            return NULL; // interrupts the program and returns NULL
        }
        line = newp; // if memory is allocated correctly stores the memory allocated to the line pointer
        if (c == '\n') // if a new line is detected
            break; // interrupts the while cycle
        line[pos++] = (char)c; // stores the character in dynamic memory and the new character in the new location.
    }
    if (line) { // if the line contains something then a null character is added at the end to complete that string.
        line[pos] = '\0';
    }
    return line; // returns the contents of the line.
}

int main(void) { // main statement
    char *str, *sub; // character punctuation statement
    size_t len1, len2, i, count = 0; // unsigned value statement "size_t is equal to unsigned int" so may also be <0
    int pos[count]; // declare a count array to insert the index then print it in reverse
    int j;

    // Here is the main string
    printf("Enter Main String: \n"); // print the entry and enter the main string
    str = my_getline(stdin); // inserts the entered string inside the pointer using my_getline function and using getchar analogue stdin to make the entered characters input from the standard input

    // here is the substring to look for
    printf("Enter substring to search: \ n"); // print the entry and enter the main substring
    sub = my_getline(stdin); // inserts the entered string inside the pointer using my_getline function and using getchar analogue stdin to make the entered characters input from the standard input

    if (str && sub) { // if string and substring && = and
        len1 = strlen(str); // inserts the string length in the len1 variable
        len2 = strlen(sub); // inserts the length of the string in the len2 variable
        for (i = 0; i + len2 <= len1; i++) { // loop for with the control that the substring is less than or equal to the main string ie len2 <= len1
            if (! memcmp(str + i, sub, len2)) { // here uses the memcmp function to compare the string and substring byte bytes
                count++; // count variable that is incremented each time the sub is found in p
                // here is where it gets in output
                // If the substring was found mold the index with the locations it was found
                pos[count] = i + 1;
                printf( "%d\n", pos[count]);
            }
        }
        // print to get reverse output
        printf("number of times%d", count);

        // print to get reverse output
        printf("%d", count);
        for (j = count - 1; j >= 0; j--)
            printf("%d", pos[j]);
 
        if (count == 0) { // if count is = 0 ie the substring was not found string string not found
            // otherwise if not found
            printf("Subtry not found \n");
        }
    }
    // free releases the memory area that was reserved for the string and substrings so that it can be reused in the next run
    free(str);
    free(sub);
    return 0; // exit analog
}

最佳答案

你的代码完全不可读。即使重新格式化并间隔开,注释也会让人很难看到重要的内容。

您应该只评论不明显的内容:int main(void) {//main statements 是无用的适得其反的评论的一个很好的例子。

删除所有注释后,代码显示出一些问题:

  • printf("输入要搜索的子字符串:\n"); 中多了一个空格

  • 数组 pos 的大小定义为 0:int count = 0; int pos[计数];。该程序具有未定义的行为。

  • count 在将偏移量存储到数组之前递增。因此,数组内容不会从索引 0 开始,因此当您在第二个循环中从 count-1 向下迭代到 0 时,会产生错误的输出.

这是一个简化且更正的版本:

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

/*
   Reads a string from the stream allocated with malloc
   stops at newline, not included in string.
   Returns NULL at EOF
 */
char *my_getline(FILE *stream) {
    char *line = NULL;
    size_t pos = 0;
    int c;

    while ((c = getc(stream)) != EOF) {
        char *newp = realloc(line, pos + 2);
        if (newp == NULL) {
            free(line);
            return NULL;
        }
        line = newp;
        if (c == '\n')
            break;
        line[pos++] = (char)c;
    }
    if (line) {
        line[pos] = '\0';
    }
    return line;
}

int main(void) {

    printf("Enter Main String:\n");
    char *str = my_getline(stdin);

    printf("Enter substring to search:\n");
    char *sub = my_getline(stdin);

    if (str && sub) {
        size_t count = 0;
        size_t len1 = strlen(str);
        size_t len2 = strlen(sub);
        size_t pos[len1 + 1];

        for (size_t i = 0; i + len2 <= len1; i++) {
            if (!memcmp(str + i, sub, len2)) {
                pos[count] = i + 1;
                printf("%d\n", (int)pos[count]);
                count++;
            }
        }
        if (count != 0) {
            printf("number of times: %d\n", (int)count);
            for (size_t j = count; j-- > 0;) {
                printf(" %d", (int)pos[j]);
            }
            printf("\n");
        } else {
            printf("substring not found.\n");
        }
    }
    free(str);
    free(sub);
    return 0;
}

关于c - C中的数组反向输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44885131/

相关文章:

c - 在C程序中获取系统命令输出

c - 在 C 中使用动态内存

c - 构建此类代码的最佳方式是什么?

C 使用指针从矩阵中提取数组

arrays - 找到最长的子数组

c# - 多个线程中的for循环

bash 遍历除给定数字以外的数字列表

c - 无法将字符串存储在结构中

c - 使用 C DLL 的 VB.Net

VB.Net 动态初始化数组