struct(.h) 에 선언값 못가져오는 문제

minnal의 이미지

//A.h
#ifndef NRDATA_H
#define NRDATA_H
#ifdef __cplusplus
extern "C" {
#endif
 
typedef struct {
	int32_t slotId;
	string IfName;
} interface_table_t;
 
interface_table_t interface_table[] = {
    {-1, "r_data0", },
 
int32_t Test_slotId = 10;
std::string  srmnet = "r_data0";
 
 
//B.cpp
#include "A.h"
std::string  T_srmnet = "r_data0";
 
bool  B::interfaceName(const std::string iName, IPinfoD** ipinfoPointer, const int32_t slotId) const
{
    LOGI("-- %s -- interfaceName = %s", __FUNCTION__, iName.c_str());
    for(int32_t i = 0; i < INTERFACE_TABLE_LENGTH; i++) {
		LOGI("-- %s -- 0 interfaceName = Test_slotId %d", __FUNCTION__, Test_slotId);   		
		LOGI("-- %s -- 0 interfaceName = Test_str %s %s", __FUNCTION__, srmnet.c_str(), T_srmnet.c_str());   
		LOGI("-- %s -- 1 interfaceName =%d, slotid = %d", __FUNCTION__, i, interface_table[i].slotId);	
		LOGI("-- %s -- 1 interfaceName =%d, %s", __FUNCTION__, i, interface_table[i].IfName.c_str());	
	       interface_table[0].IfName = "r_data0";   
		LOGI("-- %s -- 1-1 interfaceName = %s", __FUNCTION__, interface_table[0].IfName.c_str());   
 
                }
 
    }
    return ret;
}

.h 에 선언되어 구조체 설정 값 못가져오는 경우가있는데 c++ 구조체 객체는 public 데이타 아닌가요? #include 했지만 못가져 오네요

.cpp 에 test 목적으로 전역 변수 설정에도 데이타를 못가져와서 코드상의 문제인지?

build 환경 문제 인지? 체크해야 할게 있는지 도움 요청 부탁드립니다 .

[결과 ]
log info verbose 1 <12>May 20 23:14:59 - -- checkInterfaceName -- interfaceName = rmnet_data0
log info verbose 1 <12>May 20 23:14:59 - -- checkInterfaceName -- 0 interfaceName = Test_slotId 10
log info verbose 1 <12>May 20 23:14:59- -- checkInterfaceName -- 0 interfaceName = Test_str (null) (null)// 전역 변수 T_srmnet 데이타 못가져옴
log info verbose 1 <12>May 20 23:14:59 - -- checkInterfaceName -- 1 interfaceName =0, slotid = 0 // .h 구조체의 초기값 "-1" 못가져옴
log info verbose 1 <12>May 20 23:14:59 - -- checkInterfaceName -- 1 interfaceName =0, (null) //.h 구조체 초기값 "rmnet0"
log info verbose 1 <12>May 20 23:14:59 - -- checkInterfaceName -- 1-1 interfaceName = rmnet_data0

Stephen Kyoungwon Kim@Google의 이미지

구조체 객체(변수) 하나가 아니라 배열을 잡아놓고 하나만 초기화해서 그런 것 같습니다.

struct X { int a; }
와 같은 건 타입이에요.

struct X x; 라고 하면, x는 변수/객체입니다.

타입은 널리 공유될수록 좋은데 변수는 한 .cpp 파일에서만 정의하고, 나머지는 헤더 파일을 통해 extern struct X x;와 같은 식으로 declaration만 공유해서 쓰셔야 최소한 multiple definition으로 생기는 링킹 에러는 피할 수 있습니다.

minnal의 이미지

.h
typedef struct {
int32_t slotId;
string IfName;
} interface_table_t;

extern interface_table_t interface_table[1] ;// 외부변수사용

.cpp

interface_table_t interface_table[1] = {
{-1, "r_data0"}
}; //초기화값 설정

.cpp 에서 초기값 데이타를 넣으려고 합니다

이렇게가 맞는지?

라스코니의 이미지

우선 struct에서 고정형 데이터 길이를 가지고 있지 않은 멤버인 class 객체를 선언하는게 적절한지 생각해 봐야겠네요. 그 객체를 위에서와 같이 초기화(생성자를 부를 수 있는지) 가능한지도 살펴보아야 겠구요. 위의 실험을 보면 가능하지 않은 것처럼 보이네요.

그러면 저라면

typedef struct {
	int32_t slotId;
	std::string *IfName;
} interface_table_t;
 
interface_table_t interface_table[] = { {-1, new std::string("r_data0")}, };

이라고 해 볼것 같네요.
익명 사용자의 이미지

1. std::string의 크기는 고정되어 있습니다. 구현마다 크기가 조금씩 다를 수는 있겠습니다만.
물론 string이 담을 수 있는 문자열의 길이는 고정되어 있지 않은데 그건 상관없는 일이고요.

2. 제시된 코드와 같이 초기화하는 것 역시 문제 없습니다.
C++ 표준의 11.6.1 Aggregates (dcl.init.aggr) 부분을 읽어 보시길.
아니면 레퍼런스라던가. (Aggregate initialization): https://en.cppreference.com/w/cpp/language/aggregate_initialization

3. 실제로 컴파일해서 실행해 봐도 좋을겁니다.

#include <iostream>
#include <string>
using namespace std;
 
extern "C" {
    typedef struct {
        int32_t slotId;
        string IfName;
    } interface_table_t;
}
 
interface_table_t interface_table[] = {
    {-1, "r_data0", },
};
 
int main() {
	cout << interface_table[0].slotId << endl;
	cout << interface_table[0].IfName << endl;
	return 0;
}

질문자의 코드의 문제가 무엇인지는 잘 모르겠습니다만. 어디 다른 데 문제가 있는 모양이죠.

4. kldp에 무책임한 답변을 달지 말라는 규칙은 없긴 하지요.

하지만 이왕이면 답변을 달 때는 잘 알고, 혹은 잘 알아보고, 답변에 담긴 정보가 틀렸을 경우에 책임을 질 생각은 없더라도, 최대한 틀리지 않게 노력은 했다는 식으로 쓰는 게 좋지 않겠습니까?

익명 사용자의 이미지

만일을 대비해서 질문 원본을 기록으로 남겨둡니다.

http://archive.is/saMlS

ymir의 이미지

interface_table[] 에서, 초기화 된 element 는 하나이므로..
interface_table 의 element 는 한 개입니다.
따라서, interface_table[1] 은 유효하지 않은 메모리에 접근하는 것입니다.

정해진 크기의 array 를 초기화 할 때, 일부만 초기화 하는 경우..
나머지 element 들은 모두 0 으로 초기화 됩니다.

#define INTERFACE_TABLE_LENGTH 4
 
interface_table_t interface_table[INTERFACE_TABLE_LENGTH] = {
    {-1, "r_data0", },
};

위와 같이 초기화 했다면, interface_table[0] 을 제외한 나머지는 0 으로 채워질 테고..
interface_table[1].slotId 를 찍으면 정상적으로 0 이 찍힐 겁니다.

array 의 모든 element 를 0 이 아닌 다른 값으로 모두 초기화 해 주려면..
일일이 하나씩 다 초기화 해줘야 합니다.

되면 한다! / feel no sorrow, feel no pain, feel no hurt, there's nothing gained.. only love will then remain.. 『 Mizz 』

ymir의 이미지

그리고 T_srmnet.c_str() 와 같이 뭔가 값이 있어야 할 자리에, 값이 없는 경우는..
stack overflow 와 같이 boundary 를 초과해서 뭔가를 덮어 쓰는 경우에 주로 발생합니다.

질문 글에는 없지만, 어디선가 해당 변수들이 위치한 메모리를 건드렸을 가능성이 높습니다.

되면 한다! / feel no sorrow, feel no pain, feel no hurt, there's nothing gained.. only love will then remain.. 『 Mizz 』

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.