【解決方法】コードに何も表示されないのはなぜですか?


```
`#define _CRT_SECURE_NO_WARNINGS

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

#define MAX 5000

`struct Product { // declaring the structure
	char name[255];
	float price;
	int quantity;
};

void readdata(struct Product*);//prototyping the read function
void displaydata(struct Product*);//prototyping the display function

`int main()
{
	int biggest = 0;
	int i, n;
	struct Product dp[MAX];

	printf("Enter the number of products:");
	scanf("%d", &n);

	if (n<0 || n>MAX)
	{
		printf("Invalid numbers!");
	}```

	struct Product* p = (struct Product*)malloc(n * sizeof(struct Product)); // dinamically allocating memory for the structure

	for (i = 0;i < n;i++) // reading the data in main
	{
		printf("Product %d :\n", i + 1);
		readdata(&dp[i]);
		if (dp[i].quantity > biggest)
		{
			biggest = dp[i].quantity; // checking which product has the highest quantity
		}
	}

	printf("The product with the highest quantity is:\n");

	for (i = 0;i < n;i++) // displaying the data in main
	{
		if (dp[i].quantity = biggest)
		{
			displaydata(&dp[i]);//displaying the product with the highest quantity
		}
	}

	for (i = 0;i < n;i++) / freeing the memory
	{
		free(&dp[i]);
	}
      //no output at all
}`

void readdata(struct Product* p) // reading the data
{
	printf("\nName:");
	scanf("%s", p->name);
	printf("\nPrice:");
	scanf("%f", &p->price);
	printf("\nQuantity:");
	scanf("%d", &p->quantity);
}
void displaydata(struct Product* p)
{
	printf("\nName:%s", p->name);
	printf("\nPrice:%f", p->price);
	printf("\nQuantity:%d", p->quantity);
} // displaying the data```

私が試したこと:

The problem I have is that this code displays nothing.It doesn't give any errors, and it returns nothing.Can someone explain where I've made mistakes?

Basically, what I have to do in this code is to display the product with the biggest quantity on stock.

I have a code that is simillar to this one, but it works without any problem, and I don't get why this one doesn't.

Also, did I correctly allocate memory for the structure? If not, I'd gladly accept some explanation on that as well.

Thanks in advance!

解決策 1

コンパイルされないからです。

if (n<0 || n>MAX)
{
    printf("Invalid numbers!");
}```

「`」は C コードでは有効な文字ではないため、コンパイラはそのコード フラグメントの最終行を好みません。

コードがコンパイルされない場合、.EXE ファイルは生成されないため、実行するアプリにそのすべてのコードが含まれていない可能性があります。バックティックが含まれていない最後の成功したコンパイルのみです。

それらを削除して、コンパイルできるかどうかを確認してください。 そうであれば、今度はそれを実行するとどうなるか見てみましょう。 それでも期待どおりに動作しない場合は、デバッガーを使用して、実行中に何が行われているかを正確に調べてください。

解決策 2

の定義を変える MAX、5000 個の製品の詳細を入力することはありません。 より妥当な値は、おそらく 10 でしょう。また、23 行目で製品用のスペースを既に割り当てています。

C++
struct Product dp[MAX];

したがって、への呼び出しの必要はありません malloc 33行目、またはへの呼び出し free 最後に。

コメント

タイトルとURLをコピーしました