c - C语言中如何处理指针数组?

标签 c arrays

就像我在循环中声明了一个指针数组,并用它通过扫描收集一堆字符串,但是循环结束后,当我想打印出数组中的字符串时,我发现所有数组都被相同的字符串,这是我输入的最新字符串。代码如下

#include<stdio.h>

int main(){

char *array[3];
char content[10];
int time;
scanf("%d",&time);

for(int i=0;i<time;i++){
  scanf("%s",content);
  array[i]=content;


}

for(int j =0;j<time;j++){
  printf("%s\n",array[j]);
}

return 0;}

最佳答案

在每次迭代时,输入流都会复制到content,并且content的地址存储在array中。 因此 content 被一次又一次地覆盖,地址被复制到 array

的每个索引
for(int i=0;i<time;i++){
  scanf("%s",content);
  array[i]=content; //Here every array[0..time] is assigned with address of content
}

简而言之,其行为如下,

enter image description here

您需要的是每次迭代的新存储位置,它可以通过 malloc 从堆中动态分配,如下所示,

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

int main()
{
    int i;
    char content[10];
    int n;
    scanf("%d", &n);
    char*array[n];
    for (i = 0; i < n; i++) {
        scanf("%9s", content); //ensure no more than 10 letter added includeing '/0'
        char*c = malloc(strlen(content)); 
        if(c)
        {
            strncpy(c,content,strlen(content));
            array[i] = c;
        }
        else
        {
            exit(0);
        }
    }

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

    for (i = 0; i < n; i++) {
        free(array[i]);
    }

}

或通过 VLA,如下所示,

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

int main()
{
    int i;
    int n;
    scanf("%d", &n);
    char*array[n];
    char content[n][10];
    for (i = 0; i < n; i++) {
        scanf("%9s", content[i]);
        array[i] = content[i];
    }

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

关于c - C语言中如何处理指针数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59941997/

相关文章:

c - 如何衡量编译成功的文件百分比?

arrays - io_submit 等待所有 oracle dbwriter I/O

python - Numpy 数组获取不是 NaN 的数组的子集/切片

javascript - 查找两个数组中匹配元素的数量?

javascript - 使用 lodash 根据类型对多个对象进行分组

c - 为什么扫描时空字符不会添加到字符串末尾?

c++ - C 数字到文本的个数和十数问题

c - Minimax 算法并检查每个选项/跟踪 C 中的最佳移动

c - 如何在c中生成设定范围内具有均匀间隔的随机值

javascript - 从 php 获取 2 个 JSON 数组到 js