詳解C語言結構體中的char數(shù)組如何賦值
前景提示
定義一個結構體,結構體中有兩個變量,其中一個是char類型的數(shù)組,那么,怎么向這個數(shù)組中插入數(shù)據(jù),打印數(shù)據(jù)呢?
typedef struct SequenceList {
// 數(shù)組的元素
char element[20];
// 數(shù)組的長度
int length;
};定義一個結構體,結構體中有兩個變量,其中一個是char類型的數(shù)組指針,那么,怎么向這個數(shù)組中插入數(shù)據(jù),打印數(shù)據(jù)呢?
// 定義順序表結構體
typedef struct SequenceList {
char *elment;
int length;
};這里的結構體處理的步驟
- 結構體初始化
- 結構體內(nèi)數(shù)據(jù)賦值
- 結構體內(nèi)輸出數(shù)據(jù)
本著上述的原則,先對第一種類型進行操作
一.char數(shù)組類型的處理
1.結構體初始化
SequenceList L; L.element = (char*)malloc(sizeof(char)*10); L.length = 10
2.結構體內(nèi)數(shù)據(jù)賦值(簡單法)
L.elment[0] = 1;
L.elment[1] = 2;
L.elment[2] = 3;
L.elment[3] = 4;
L.elment[4] = 5;
for循環(huán)
for (int i = 0; i < 10; i++)
{
L.elment[i] = i+1;
}
3.結構體內(nèi)輸出數(shù)據(jù)
for (int i = 0; i < 10; i++)
{
//不會打印空值
if (L.elment[i]>0) {
printf("element[%d] = %d\n",i, L.elment[i]);
}
}
二.char數(shù)組指針類型的處理
1.結構體初始化
//結構體初始化 MyList L; L.length = LENGTH; L.elment = (char*)malloc(L.length * sizeof(char));
2.結構體內(nèi)數(shù)據(jù)賦值
//結構體賦值
for (int i = 0; i < LENGTH; i++)
{
*(L.elment + i) = 'A' + i;
}
3.結構體內(nèi)輸出數(shù)據(jù)
//打印結構體中的值
for (int i = 0; i < LENGTH; i++)
{
if (*(L.elment + i) > 0) {
printf("elment[%d] = %c\n", i, *(L.elment + i));
}
}
三.全部代碼
1. char數(shù)組
// 010.順序表_004.cpp : 此文件包含 "main" 函數(shù)。程序執(zhí)行將在此處開始并結束。
//
#include <iostream>
#define MAXSIZE 10
typedef struct SequenceList {
// 數(shù)組的元素
char element[MAXSIZE];
// 數(shù)組的長度
int length;
};
int main()
{
// 1.初始化結構體
SequenceList *L;
L = (SequenceList*)malloc(sizeof(char)*MAXSIZE);
L->length = MAXSIZE;
// 2.存入結構體內(nèi)值
for (int i = 0; i < MAXSIZE; i++)
{
L->element[i] = 'a' + i;
}
// 3.打印結構體內(nèi)的值
for (int i = 0; i < MAXSIZE; i++)
{
if (*(L->element + i) > 0) {
printf("elment[%d] = %c\n", i, *(L->element + i));
}
}
}
2. char數(shù)組指針
// 011.順序表_005.cpp : 此文件包含 "main" 函數(shù)。程序執(zhí)行將在此處開始并結束。
//
#include <iostream>
#define MAXSIZE 10
typedef struct SequenceList {
// 數(shù)組的元素
char *element;
// 數(shù)組的長度
int length;
};
int main()
{
// 1.結構體初始化
SequenceList L;
L.length = MAXSIZE;
L.element = (char*)malloc(L.length * sizeof(MAXSIZE));
// 2.結構體內(nèi)賦值
for (int i = 0; i < MAXSIZE; i++)
{
*(L.element + i) = 'a' + i;
}
// 3.打印結構體中的值
for (int i = 0; i < MAXSIZE; i++)
{
if (*(L.element + i) > 0) {
printf("elment[%d] = %c\n", i, *(L.element + i));
}
}
}
結語這就是最近遇到的問題,這個問題困擾了很久,相信許多的初學者也遇到了這樣的問題,但是,網(wǎng)上的描述根本不怎么好用,所以,希望本博主遇到的這個問題能幫助到你
總結
到此這篇關于C語言結構體中的char數(shù)組如何賦值的文章就介紹到這了,更多相關C語言結構體中char數(shù)組賦值內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C++實現(xiàn)LeetCode(190.顛倒二進制位)
這篇文章主要介紹了C++實現(xiàn)LeetCode(190.顛倒二進制位),本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下2021-08-08
C++11 std::shared_ptr總結與使用示例代碼詳解
這篇文章主要介紹了C++11 std::shared_ptr總結與使用,本文通過示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06

