【问题标题】:dynamic allocation string C动态分配字符串 C
【发布时间】:2021-03-12 02:42:32
【问题描述】:

我希望用户输入 3 个名称,然后在程序打印这 3 个名称之后 谁能告诉我为什么不打印任何东西??? 我尝试了一切 如果有人能解释一下...... 没有错误,插入字符串后直接退出

#include <stdio.h>
#include <stdlib.h>
int main(){
int i, a, componentes;
char *nome;
componentes = 3;
nome = (char*) malloc(sizeof(char)*100);
printf("\n");
for(i = 0; i < componentes; i++){
// printf("String %d: ", i+1);
scanf("%s", &nome[i]);     
}

printf("\n");
for(a = 0; a < componentes; a++){       
printf("%s\n", nome[i]);
}
return 0;
} 

【问题讨论】:

  • scanf("%s", &amp;nome[i]); 您只有 one 字符串的缓冲区,而不是 3。&amp;nom[i] 每次迭代都指向同一个缓冲区中的某个位置。同样printf("%s\n", nome[i]); 是完全错误的,编译器应该给你一个警告。 nom[i] 是单个 char 不是字符串。
  • 如果你想扫描多个字符串,你需要分配一个二维数组。进行搜索。例如:dynamic memory for 2D char array
  • 考虑使用 fgets() 而不是 scanf()。后者易受字符串缓冲区溢出的影响。使用#define 而不是组件的变量。还要熟悉 const 关键字。它会帮助你。

标签: arrays c string


【解决方案1】:

我修复了提出的问题(加上释放内存):

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

#define N 3
#define LEN 100

int main() {
    char *components[N];
    for(int i = 0; i < N; i++) {
        components[i] = malloc(LEN);
        fgets(components[i], LEN, stdin);
    }
    for(int i = 0; i < N; i++) {
        printf("%s", components[i]);
        free(components[i]);
    }
    return 0;
}

您还可以通过堆栈上的局部变量为 3 个字符串分配 300 个字节,可以使用 char components[N][LEN]; 或作为索引的单个字符串,以向您展示不同的方式:

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

#define N 3
#define LEN 100

int main() {
    char components[N * LEN];
    for(int i = 0; i < N; i++) {
        fgets(components + i * LEN, LEN, stdin);
    }
    for(int i = 0; i < N; i++) {
        printf("%s", components + i * LEN);
    }
    return 0;
}

【讨论】:

    猜你喜欢
    • 2020-10-09
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 2015-07-14
    • 1970-01-01
    • 1970-01-01
    • 2013-03-09
    相关资源
    最近更新 更多