【问题标题】:Array of Pointers - temporary array being created at the same location which changes the previous saved content value指针数组 - 在更改先前保存的内容值的同一位置创建临时数组
【发布时间】:2020-06-20 13:10:23
【问题描述】:

我正在尝试编写一个程序,该程序可以接收用户的输入(名字、姓氏、分数)并在接受所有这样的输入后打印它。

fname1 lname1 : 99
fname2 lname2 : 23
fname3 lname3 : 29
//Note that all of them are input 

我编写了以下程序,它可以工作,但会打印最后一次输入 n 次。我知道问题是什么,但不知道如何解决。 临时数组变量每次都在完全相同的位置创建,它使所有元素都相同。 如何解决?

#include <stdio.h>
#define LENGTH 3

int main() {
    int *score[LENGTH];
    char *fname[LENGTH];
    char *lname[LENGTH];

    for(int i = 0; i < LENGTH; i++){
        printf("Enter name and score of batter %d: ",i);
        char ftemp[10];
        char ltemp[10];
        int tempScore;

        scanf("%s %s %d", ftemp, ltemp, &tempScore);
        fname[i] = ftemp;
        lname[i] = ltemp;
        score[i] = &tempScore;
    }

    for(int i = 0; i < LENGTH; i++){
        printf("%s %s %d\n", fname[i], lname[i], *score[i]);
    }
} 

【问题讨论】:

  • 您需要复制而不是分配指针。请参阅strncpy
  • 大错特错。永远不要使用 strncpy。真正的问题是没有分配内存。
  • @gnasher729 能不能详细解释一下?

标签: c arrays pointers scanf


【解决方案1】:

我认为您正在尝试将对局部变量的引用分配给 score、fname 和 lname 。您不能这样做,因为它会在退出其范围时破坏,而不是尝试这样做

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LENGTH 3

int main() {
    int *score[LENGTH];
    char *fname[LENGTH];
    char *lname[LENGTH];

    for(int i = 0; i < LENGTH; i++){
        printf("Enter name and score of batter %d: ",i+1);
        char ftemp[10];
        char ltemp[10];
        int tempScore;

        scanf("%s %s %d", ftemp, ltemp, &tempScore);
        fname[i] = malloc(strlen(ftemp) + 1);
        lname[i] = malloc(strlen(ltemp) + 1);
        score[i] = malloc(sizeof(int));

        if(fname[i]==NULL||lname[i]==NULL||score[i]==NULL)
        {
            if(fname[i]!=NULL)
                  free(fname[i]);
            if(lname[i]!=NULL)
                  free(lname[i]);
            if(score[i]!=NULL)
                  free(score[i]);
            printf("Memory Error");
            exit(1);
        }
        else
        {
            strcpy(fname[i],ftemp);
            strcpy(lname[i],ltemp);
            *score[i]=tempScore;
        }
    }

    for(int i = 0; i < LENGTH; i++){
        printf("%s %s %d\n", fname[i], lname[i], *score[i]);
   }
}

【讨论】:

  • 我非常喜欢对三个指针使用局部变量,并且只在完成后才存储它们。使代码更具可读性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-09
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
  • 2012-10-17
相关资源
最近更新 更多