Difference between const char *p, char * const p and const ...

文章推薦指數: 80 %
投票人數:10人

1. const char *ptr : This is a pointer to a constant character. You cannot change the value pointed by ptr, but you can change the pointer ... Skiptocontent CoursesForWorkingProfessionalsLIVEDSALiveClassesSystemDesignJavaBackendDevelopmentFullStackLIVEExploreMoreSelf-PacedDSA-SelfPacedSDETheoryMust-DoCodingQuestionsExploreMoreForStudentsLIVECompetitiveProgrammingDataStructureswithC++DataScienceExploreMoreSelf-PacedDSA-SelfPacedCIPJAVA/Python/C++ExploreMoreSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGoLanguageHTMLCSSKotlinML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebTechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesChemistryNotesClass8NotesClass9NotesClass10NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsStudentChapterGeekontheTopInternshipCareersJobsApplyforJobsPostaJobHirewithUsKnowaboutJobathonJobathonPracticeAllDSAProblemsProblemoftheDayInterviewSeries:WeeklyContestsBi-WizardCoding:SchoolContestsContestsandEventsPracticeSDESheetCuratedDSAListsTop50ArrayProblemsTop50StringProblemsTop50TreeProblemsTop50GraphProblemsTop50DPProblems ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningHTMLSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesDifferencebetweenconstchar*p,char*constpandconstchar*constpPointertoanArray|ArrayPointerDifferencebetweenpointertoanarrayandarrayofpointersStorageforStringsinCC++stringclassanditsapplicationsPointersinCandC++|Set1(Introduction,ArithmeticandArray)ReferencesinC++ObjectOrientedProgramminginC++auto_ptr,unique_ptr,shared_ptr,weak_ptrPointersinCandC++PointersinC/C++withExamplesC++ClassesandObjectsAccessModifiersinC++InheritanceinC++VirtualFunctionsandRuntimePolymorphisminC++VirtualFunctioninC++PolymorphisminC++EncapsulationinC++AbstractioninC++StructurevsclassinC++CanaC++classhaveanobjectofselftype?WhyistheSizeofanEmptyClassNotZeroinC++?StaticdatamembersinC++SomeinterestingfactsaboutstaticmemberfunctionsinC++FriendclassandfunctioninC++ArraysinC/C++DynamicMemoryAllocationinCusingmalloc(),calloc(),free()andrealloc()std::sort()inC++STLBitwiseOperatorsinC/C++CoreDump(Segmentationfault)inC/C++Differencebetweenconstchar*p,char*constpandconstchar*constpPointertoanArray|ArrayPointerDifferencebetweenpointertoanarrayandarrayofpointersStorageforStringsinCC++stringclassanditsapplicationsPointersinCandC++|Set1(Introduction,ArithmeticandArray)ReferencesinC++ObjectOrientedProgramminginC++auto_ptr,unique_ptr,shared_ptr,weak_ptrPointersinCandC++PointersinC/C++withExamplesC++ClassesandObjectsAccessModifiersinC++InheritanceinC++VirtualFunctionsandRuntimePolymorphisminC++VirtualFunctioninC++PolymorphisminC++EncapsulationinC++AbstractioninC++StructurevsclassinC++CanaC++classhaveanobjectofselftype?WhyistheSizeofanEmptyClassNotZeroinC++?StaticdatamembersinC++SomeinterestingfactsaboutstaticmemberfunctionsinC++FriendclassandfunctioninC++ArraysinC/C++DynamicMemoryAllocationinCusingmalloc(),calloc(),free()andrealloc()std::sort()inC++STLBitwiseOperatorsinC/C++CoreDump(Segmentationfault)inC/C++Differencebetweenconstchar*p,char*constpandconstchar*constpViewDiscussion ImproveArticle SaveArticle LikeArticle DifficultyLevel: EasyLastUpdated: 11Sep,2021Prerequisite:Pointers Thereisalotofconfusionwhenchar,const,*,pareallusedindifferentpermutationsandmeaningschangeaccordingtowhichisplacedwhere.Followingarticlefocusondifferentiationandusageofallofthese. Thequalifierconstcanbeappliedtothedeclarationofanyvariabletospecifythatitsvaluewillnotbechanged.constkeywordappliestowhateverisimmediatelytoitsleft.Ifthereisnothingtoitsleft,itappliestowhateverisimmediatelytoitsright. 1.constchar*ptr:Thisisapointertoaconstantcharacter.Youcannotchangethevaluepointedbyptr,butyoucanchangethepointeritself.“constchar*”isa(non-const)pointertoaconstchar.C//Cprogramtoillustrate//charconst*p#include#include intmain(){    chara='A',b='B';    constchar*ptr=&a;         //*ptr=b;illegalstatement(assignmentofread-onlylocation*ptr)         //ptrcanbechanged    printf("valuepointedtobyptr:%c\n",*ptr);    ptr=&b;    printf("valuepointedtobyptr:%c\n",*ptr);}Output: valuepointedtobyptr:A valuepointedtobyptr:BNOTE:Thereisnodifferencebetweenconstchar*pandcharconst*pasbotharepointertoaconstcharandpositionof‘*'(asterik)isalsosame.  2.char*constptr:Thisisaconstantpointertonon-constantcharacter.Youcannotchangethepointerp,butcanchangethevaluepointedbyptr. C//Cprogramtoillustrate//char*constp#include#include intmain(){    chara='A',b='B';    char*constptr=&a;    printf("Valuepointedtobyptr:%c\n",*ptr);    printf("Addressptrispointingto:%d\n\n",ptr);     //ptr=&b;illegalstatement(assignmentofread-onlyvariableptr)     //changingthevalueattheaddressptrispointingto    *ptr=b;    printf("Valuepointedtobyptr:%c\n",*ptr);    printf("Addressptrispointingto:%d\n",ptr);}Output: Valuepointedtobyptr:A Addressptrispointingto:-1443150762 Valuepointedtobyptr:B Addressptrispointingto:-1443150762NOTE:Pointeralwayspointstosameaddress,onlythevalueatthelocationischanged. 3.constchar*constptr:Thisisaconstantpointertoconstantcharacter.Youcanneitherchangethevaluepointedbyptrnorthepointerptr. C//Cprogramtoillustrate//constchar*constptr#include#include intmain(){    chara='A',b='B';    constchar*constptr=&a;         printf("Valuepointedtobyptr:%c\n",*ptr);    printf("Addressptrispointingto:%d\n\n",ptr);     //ptr=&b;illegalstatement(assignmentofread-onlyvariableptr)    //*ptr=b;illegalstatement(assignmentofread-onlylocation*ptr) }Output: Valuepointedtobyptr:A Addressptrispointingto:-255095482NOTE:charconst*constptrissameasconstchar*constptr. QuizonconstkeywordThisarticleiscontributedbyYashSingla.IfyoulikeGeeksforGeeksandwouldliketocontribute,youcanalsowriteanarticleusingwrite.geeksforgeeks.orgormailyourarticletoreview-team@geeksforgeeks.org.SeeyourarticleappearingontheGeeksforGeeksmainpageandhelpotherGeeks.Pleasewritecommentsifyoufindanythingincorrect,oryouwanttosharemoreinformationaboutthetopicdiscussedabove. MyPersonalNotes arrow_drop_upSave LikeNext PointertoanArray|ArrayPointerRecommendedArticlesPage:19,Dec1807,Aug1416,Nov1529,Jul1415,Oct1906,Sep1726,Nov1002,Oct1203,Oct1122,Sep1327,Aug1328,Aug1330,Aug1305,Feb1430,Jul1405,Sep1825,Oct1803,Apr2018,Aug2002,Feb2131,May1405,Oct1821,May1706,Jan21ArticleContributedBy:GeeksforGeeksVotefordifficultyCurrentdifficulty: EasyEasy Normal Medium Hard ExpertImprovedBy:DeepankarMullickadnanirshad158ArticleTags:C-PointerBasicscpp-pointerCLanguageC++PracticeTags:CPPReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsWhat'sNewViewDetailsViewDetailsViewDetailsMostpopularinCLanguageSubstringinC++MultidimensionalArraysinC/C++LeftShiftandRightShiftOperatorsinC/C++std::stringclassinC++DifferentMethodstoReverseaStringinC++MostvisitedinC++VectorinC++STLPriorityQueueinC++StandardTemplateLibrary(STL)MapinC++StandardTemplateLibrary(STL)InitializeavectorinC++(7differentways)SubstringinC++ImproveyourCodingSkillswithPracticeTryIt! Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register



請為這篇文章評分?